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

Viewed 4180

I am working a lot with nodes before they are attached to the main page's DOM; and I need to perform some work depending on whether or not a given node is contained within the main document or not.

My current method is to walk up the parents, via:

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

Is there a more appropriate way to do this? (Preferrably one that doesn't have to walk all of the node's ancestors?)

3 Answers

The modern, vanilla answer is to use Node.isConnected:

let test = document.createElement('p');
console.log(test.isConnected); // Returns false
document.body.appendChild(test);
console.log(test.isConnected); // Returns true

(example taken directly from the MDN docs)

Related