Reputation: 2879
var myElement = document.querySelector('div.example');// <div..></div>
/*
* A lot time after, codes executed, whatever
*/
if( myElement.isInDocument )
{
// Do something
}
Is there a easy way to know if 'myElement' still in document?
Upvotes: 1
Views: 3525
Reputation: 2811
For modern browsers the answer is myElement.isConnected
https://developer.mozilla.org/en-US/docs/Web/API/Node/isConnected
Upvotes: 0
Reputation: 707318
You can first see if the .contains()
method exists and use it if available. If not, walk the parent chain looking for the document object. From a prior project using code like this, you can't just rely on parentNode being empty (in some versions of IE) when you get to document so you have to also explicitly check for document like this:
function isInDocument(e) {
if (document.contains) {
return document.contains(e);
} else {
while (e.parentNode && e !== document) {
e = e.parentNode;
}
return e === document;
}
}
Upvotes: 1
Reputation: 207501
One way is to use contains()
var myElement = document.querySelector('div.example');
console.log("elment ", myElement);
console.log("contains before ", document.body.contains(myElement));
myElement.parentNode.removeChild(myElement);
console.log("contains after ", document.body.contains(myElement));
Upvotes: 1
Reputation: 106640
function isInPage(node) {
return (node === document.body) ? false : document.body.contains(node);
}
Upvotes: 8
Reputation: 324630
Since every element in the document is a child of the document, check to see if your element is:
function isInDocument(e) {
while( e.parentNode) e = e.parentNode;
return e === document;
}
Upvotes: 6