Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>UPDATE: For anyone interested in it, here is the implementation I finally used:</p> <pre><code>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; } </code></pre> <p>The reason I wanted this is to provide a way of synthesizing the <code>onload</code> event for DOM elements. Here is that function (although I am using something slightly different because I am using it in conjunction with <a href="http://www.mochikit.com/" rel="nofollow noreferrer"><strong>MochiKit</strong></a>):</p> <pre><code>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); } } </code></pre> <p>For an example, this setup could be used as follows:</p> <pre><code>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 </code></pre> <p>Hope that is useful to someone.</p> <p>NOTE: the reason I ended up with this solution rather than <a href="https://stackoverflow.com/questions/220188/how-can-i-determine-if-a-dynamically-created-dom-element-has-been-added-to-the-do/220224#220224"><strong>Darryl's answer</strong></a> 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.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload