How can I determine if a node is in memory or in dom?

I work a lot with nodes before they are attached to the DOM main page; and I need to do some work depending on whether the given node is contained in the main document or not.

My current method is to approach the parents using:

if this.el$.closest("body").length > 0

Is there a more suitable way to do this? (Preferably one that should not walk all the ancestors of the node?)

+5
source share
2 answers

You have several options that run at several different speeds.

var $document = $(document);
var $element = $("#jq-footer");
var exists;

// Test if the element is within a body
exists = $element.closest("body").length;

// Test if the document contains an element
// wrong syntax, use below instead --> exists = $.contains($document, $element);
exists = $.contains(document.documentElement, $element[0]);

// Test if the element is within a body
$($element).parents().is("body");

// Manually loop trough the elements
exists = elementExists($element[0]);

// Used for manual loop
function elementExists(element) {
    while (element) {
        if (element == document) {
            return true;
        }
        element = element.parentNode;
    }
    return false;
}​

See Performance Test

html, , jQuery , script, html .

"" , .

, , true, . true, , , , false.

exists = $.contains(document.documentElement, $element[0]);

, MrOBrian , , .

MrOBrian.

jsPerf .

Felix Kling , jsPerf.

, :
jsPerf: dom-tree-test-exists

+7

:

var id = element.id || generateRandomId(); // some function generating a random string
if(document.getElementById(id) !== null) {
    // element in tree
}

, , node. , .

:

, node while , ( ). node () , node , -, Chrome 21.

, Firefox 14 Node#contains [MDN] , - .

Firefox ID .contains, -, Chrome, :

function in_tree(element) {
    if(!element || !element.parentNode) { // fail fast
        return false;
    }
    if(element.contains) {
        return document.body.contains(element);
    }
    var id = element.id || generateRandomId();
    element.id = id;
    return document.getElementById(id) !== null;
}

, .

+3

All Articles