Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if a DOM element mounted to tree

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?

like image 250
Kuan Avatar asked Jan 06 '16 18:01

Kuan


2 Answers

You can probably try this one

document.body.contains(yourDiv)

contains method will return true or false

like image 172
readysteady Avatar answered Oct 08 '22 04:10

readysteady


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');
}
like image 36
dandavis Avatar answered Oct 08 '22 06:10

dandavis