javascript – How to know if a DOM element mounted to tree-ThrowExceptions

Exception or error:

I am pretty new to DOM, I wonder if I refer a DOM element which may be removed from DOM tree, how can I check if it is still mounted or not?

Like:

var div = document.createElement("DIV");
document.body.appendChild(div);

Then later I probably select <div> element and remove it, but this operation does only unmount those from the tree, the div variable still points to that DOM element.

I wonder if there is a function to test if the div is still on the page (mounted on the DOM tree) or not?

How to solve:

You can probably try this one

document.body.contains(yourDiv)

contains method will return true or false

###

if a node is part of the document, its baseURI property will be a string URL, otherwise, it will be null

var div = document.createElement("DIV"), 
u1=div.baseURI, u2, u3; //first url, un-attached
document.body.appendChild(div);
u2=div.baseURI; //second url, attached
div.remove();
u3=div.baseURI; //third url, detached
alert(JSON.stringify([u1,u2,u3], null, 2));

run on this page in devtools shows:

[
  null,
  "http://stackoverflow.com/questions/34640316/how-to-know-if-a-dom-element-mounted-to-tree",
  null
]

this means that to determine if a node is attached, you can simply ask for elm.baseURI:

if(div.baseURI){ 
   alert('attached')
 }else{
   alert('not attached');
}

###

According to the improved version of Mr Lister.

function isMounted(node) {
    if (node.nodeType === Node.DOCUMENT_NODE) return true;
    if (node.parentNode == undefined) return false;
    return isMounted(node.parentNode);
}

###

Володимир Яременко’s answer is correct, but as an alternative method, you can check if the div has a parent node.

if (theDiv.parentNode==null) {
  // Not in the DOM tree
}
else {
  // in the DOM tree!
}

This will be null before appending it to the body, and again after removing it from the body.

###

You can use Node.isConnected

div.isConnected

Note: This will not work with old browsers (Internet Explorer, Edge < 79, Safari < 10)

Leave a Reply

Your email address will not be published. Required fields are marked *