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?
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');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With