Ratata Tata
Ratata Tata

Reputation: 2879

Can I know if element is in document or not?

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

Answers (5)

Daniel Lewis
Daniel Lewis

Reputation: 2811

For modern browsers the answer is myElement.isConnected

https://developer.mozilla.org/en-US/docs/Web/API/Node/isConnected

Upvotes: 0

jfriend00
jfriend00

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

epascarello
epascarello

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));

JSFiddle

Upvotes: 1

David Sherret
David Sherret

Reputation: 106640

From Mozilla:

function isInPage(node) {
  return (node === document.body) ? false : document.body.contains(node);
}

Upvotes: 8

Niet the Dark Absol
Niet the Dark Absol

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

Related Questions