简体   繁体   中英

How can I determine if a dynamically-created DOM element has been added to the DOM?

According to spec , only the BODY and FRAMESET elements provide an "onload" event to attach to, but I would like to know when a dynamically-created DOM element has been added to the DOM in JavaScript.

The super-naive heuristics I am currently using, which work, are as follows:

  • Traverse the parentNode property of the element back until I find the ultimate ancestor (ie parentNode.parentNode.parentNode.etc until parentNode is null)

  • If the ultimate ancestor has a defined, non-null body property

    • assume the element in question is part of the dom
  • else

    • repeat these steps again in 100 milliseconds

What I am after is either confirmation that what I am doing is sufficient (again, it is working in both IE7 and FF3) or a better solution that, for whatever reason, I have been completely oblivious to; perhaps other properties I should be checking, etc.


EDIT: I want a browser-agnostic way of doing this, I don't live in a one-browser world, unfortunately; that said, browser-specific information is appreciated, but please note which browser you know that it does work in. Thanks!

UPDATE: For anyone interested in it, here is the implementation I finally used:

function isInDOMTree(node) {
   // If the farthest-back ancestor of our node has a "body"
   // property (that node would be the document itself), 
   // we assume it is in the page's DOM tree.
   return !!(findUltimateAncestor(node).body);
}
function findUltimateAncestor(node) {
   // Walk up the DOM tree until we are at the top (parentNode 
   // will return null at that point).
   // NOTE: this will return the same node that was passed in 
   // if it has no ancestors.
   var ancestor = node;
   while(ancestor.parentNode) {
      ancestor = ancestor.parentNode;
   }
   return ancestor;
}

The reason I wanted this is to provide a way of synthesizing the onload event for DOM elements. Here is that function (although I am using something slightly different because I am using it in conjunction with MochiKit ):

function executeOnLoad(node, func) {
   // This function will check, every tenth of a second, to see if 
   // our element is a part of the DOM tree - as soon as we know 
   // that it is, we execute the provided function.
   if(isInDOMTree(node)) {
      func();
   } else {
      setTimeout(function() { executeOnLoad(node, func); }, 100);
   }
}

For an example, this setup could be used as follows:

var mySpan = document.createElement("span");
mySpan.innerHTML = "Hello world!";
executeOnLoad(mySpan, function(node) { 
   alert('Added to DOM tree. ' + node.innerHTML);
});

// now, at some point later in code, this
// node would be appended to the document
document.body.appendChild(mySpan);

// sometime after this is executed, but no more than 100 ms after,
// the anonymous function I passed to executeOnLoad() would execute

Hope that is useful to someone.

NOTE: the reason I ended up with this solution rather than Darryl's answer was because the getElementById technique only works if you are within the same document; I have some iframes on a page and the pages communicate between each other in some complex ways - when I tried this, the problem was that it couldn't find the element because it was part of a different document than the code it was executing in.

The most straightforward answer is to make use of the Node.contains method, supported by Chrome, Firefox (Gecko), Internet Explorer, Opera, and Safari. Here is an example:

var el = document.createElement("div");
console.log(document.body.contains(el)); // false
document.body.appendChild(el);
console.log(document.body.contains(el)); // true
document.body.removeChild(el);
console.log(document.body.contains(el)); // false

Ideally, we would use document.contains(el) , but that doesn't work in IE, so we use document.body.contains(el) .

Unfortunately, you still have to poll, but checking whether an element is in the document yet is very simple:

setTimeout(function test() {
  if (document.body.contains(node)) {
    func();
  } else {
    setTimeout(test, 50);
  }
}, 50);

If you're okay with adding some CSS to your page, here's another clever technique that uses animations to detect node insertions: http://www.backalleycoder.com/2012/04/25/i-want-a-damnodeinserted/

Instead of walking the DOM tree up to the document element just use element.ownerDocument . see here: https://developer.mozilla.org/en-US/docs/DOM/Node.ownerDocument and do this:

element.ownerDocument.body.contains(element)

and you're good.

Can you no do a document.getElementById('newElementId'); and see if that returns true. If not, like you say, wait 100ms and try again?

You could query document.getElementsByTagName("*").length or create a custom appendChild function like the folllowing:

var append = function(parent, child, onAppend) {
  parent.appendChild(child);
  if (onAppend) onAppend(child);
}

//inserts a div into body and adds the class "created" upon insertion
append(document.body, document.createElement("div"), function(el) {
  el.className = "created";
});

Update

By request, adding the information from my comments into my post

There was a comment by John Resig on the Peppy library on Ajaxian today that seemed to suggest that his Sizzle library might be able to handle DOM insertion events. I'm curious to see if there will be code to handle IE as well

Following on the idea of polling, I've read that some element properties are not available until the element has been appended to the document (for example element.scrollTop), maybe you could poll that instead of doing all the DOM traversal.

One last thing: in IE, one approach that might be worth exploring is to play with the onpropertychange event. I reckon appending it to the document is bound to trigger that event for at least one property.

In a perfect world you could hook the mutation events. I have doubts that they work reliably even on standards browsers. It sounds like you've already implemented a mutation event so you could possibly add this to use a native mutation event rather than timeout polling on browsers that support those.

I've seen DOM-change implementations that monitor changes by comparing document.body.innerHTML to last saved .innerHTML , which isn't exactly elegant (but works). Since you're ultimately going to check if a specific node has been added yet, then you're better off just checking that each interrupt.

Improvements I can think of are using .offsetParent rather than .parentNode as it will likely cut a few parents out of your loop (see comments). Or using compareDocumentIndex() on all but IE and testing .sourceIndex propery for IE (should be -1 if node isn't in the DOM).

This might also help: X browser compareDocumentIndex implementaion by John Resig .

You want the DOMNodeInserted event (or DOMNodeInsertedIntoDocument ).

Edit: It is entirely possible these events are not supported by IE, but I can't test that right now.

A MutationObserver is what you should use to detect when an element has been added to the DOM. MutationObservers are now widely supported across all modern browsers (Chrome 26+, Firefox 14+, IE11, Edge, Opera 15+, etc).

Here's a simple example of how you can use a MutationObserver to listen for when an element is added to the DOM.

For brevity, I'm using jQuery syntax to build the node and insert it into the DOM.

var myElement = $("<div>hello world</div>")[0];

var observer = new MutationObserver(function(mutations) {
   if (document.contains(myElement)) {
        console.log("It's in the DOM!");
        observer.disconnect();
    }
});

observer.observe(document, {attributes: false, childList: true, characterData: false, subtree:true});

$("body").append(myElement); // console.log: It's in the DOM!

The observer event handler will trigger whenever any node is added or removed from the document . Inside the handler, we then perform a contains check to determine if myElement is now in the document .

You don't need to iterate over each MutationRecord stored in mutations because you can perform the document.contains check directly upon myElement .

To improve performance, replace document with the specific element that will contain myElement in the DOM.

var finalElement=null; 

I am building dom objects in a loop, when the loop is on the last cycle and the lastDomObject is created then:

 finalElement=lastDomObject; 

leave loop:

while (!finalElement) { } //this is the delay... 

The next action can use any of the newly created dom objects. It worked on the first try.

Here is another solution to the problem extracted from the jQuery code. The following function can be used to check if a node is attached to the DOM or if it is "disconnected".

function isDisconnected( node ) {
    return !node || !node.parentNode || node.parentNode.nodeType === 11;
}

A nodeType === 11 defines a DOCUMENT_FRAGMENT_NODE, which is a node not connected to the document object.

For further information see the following article by John Resig: http://ejohn.org/blog/dom-documentfragments/

Neither of DOMNodeInserted or DOMNodeInsertedIntoDocument events is supported in IE. Another missing from IE [only] feature of DOM is compareDocumentPosition function that is designed to do what its name suggests.

As for the suggested solution, I think there is no better one (unless you do some dirty tricks like overwriting native DOM members implementations)

Also, correcting the title of the question: dynamically created Element is part of the DOM from the moment it is created, it can be appended to a document fragment, or to another element, but it might not be appended to a document.

I also think that the problem you described is not the problem that you have, this one looks to be rather one of the potential solutions to you problem. Can you probably explain in details the use case?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM