Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: how to tell if a node object has been inserted into a document/another element yet

I'd like to be able to identify whether a given DOM node has been appended/inserted into another node yet, or whether it is fresh out of document.createElement() or similar and has not been placed anywhere.

In most browsers just checking the parentNode works.

if (!node.parentNode) {
  // this node is not part of a larger document
}

However, in Internet Explorer it appears that new elements, even right after they've been created with document.createElement() already have a parentNode object (of type DispHTMLDocument??).

Any other nice cross-browser and reliable way?

Edit: looks like Internet Explorer is implicitly creating a DocumentFragment (with nodeType of 11) and setting that as the node's parentNode property.

like image 911
thomasrutter Avatar asked Apr 12 '10 05:04

thomasrutter


1 Answers

I think that even without IE's foibles, checking for the presence of parentNode might not be enough. For example:

var d = document.createElement('div');
var s = document.createElement('span');
d.appendChild(s);
if (s.parentNode) {
    // this will run though it's not in the document
}

If something is in the document, then eventually one of its ancestors will be the document itself. Try this out and see how it goes:

function inDocument(node) {
    var curr = node;
    while (curr != null) {
        curr = curr.parentNode;
        if (curr == document) return true;
    }
    return false;
}

// usage: 
// if (inDocument(myNode)) { .. }

If you only want to check to a certain depth - that is, you know that your newly created elements aren't going to be nested any further than IE's Fragment, try this:

function inDocument(node, depth) {
    depth = depth || 1000;
    var curr = node;
    while ((curr != document) && --depth) {
        curr = curr.parentNode;
        if (curr == null) return false;
    }
    return true;
}

inDocument(myNode, 2);  // check only up to two deep.
inDocument(myNode);     // check up to 1000 deep.
like image 112
nickf Avatar answered Oct 14 '22 17:10

nickf