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?


var div = document.createElement("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


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
u2=div.baseURI; //second url, attached
u3=div.baseURI; //third url, detached
alert(JSON.stringify([u1,u2,u3], null, 2));

run on this page in devtools shows:


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

   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


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 *