Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML element is attached to a document

When an element is removed from the DOM using removeChild(), the reference to the element still exist but the element is no more in the DOM.
How to know if an HTML element (or its parents) is still attached to a document ?

like image 644
Franck Freiburger Avatar asked Apr 13 '11 12:04

Franck Freiburger


People also ask

What is HTML DOM element?

The HTML DOM is an Object Model for HTML. It defines: HTML elements as objects. Properties for all HTML elements. Methods for all HTML elements.

What is document in HTML?

The document object is the root node of the HTML document. The document object is a property of the window object. The document object is accessed with: window.document or just document.

Which HTML element defines the title of a document?

The <title> HTML element defines the document's title that is shown in a browser's title bar or a page's tab. It only contains text; tags within the element are ignored. Metadata content.


2 Answers

Node.prototype.contains() is the answer:

if(document.body.contains(yourElement)) {
    // Yep, it's attached.
}

Compatibility: IE5+

like image 200
fregante Avatar answered Oct 08 '22 18:10

fregante


For newer browsers (no IE support), you can use Node.isConnected, which is a property on Node and returns a boolean.

Mozilla Node.isConnected

document.querySelectorAll('#myElement').isConnected;
like image 23
slimeygecko Avatar answered Oct 08 '22 19:10

slimeygecko