How can a JavaScript developer programmatically check if a specific DOM node is currently attached to the document?

Question

Grade: Education Subject: Support
How can a JavaScript developer programmatically check if a specific DOM node is currently attached to the document?
Asked by:
115 Viewed 115 Answers

Answer (115)

Best Answer
(1034)
A JavaScript developer can check if a DOM node is attached to the document using several methods: 1. **`Node.prototype.isConnected` (Modern & Recommended):** This is the most direct and efficient way. `element.isConnected` returns `true` if the node is connected to a document (i.e., it's in the DOM tree), and `false` otherwise. Example: `if (myElement.isConnected) { console.log('Element is in the DOM'); }` 2. **`document.body.contains(element)`:** This checks if the `document.body` (or any other known ancestor like `document.documentElement`) contains the given `element`. While effective for elements within the ``, it might not work for elements in ``. Example: `if (document.body.contains(myElement)) { console.log('Element is a descendant of body'); }` 3. **`element.parentNode !== null`:** A node that has been detached from the DOM will typically have `null` as its `parentNode`. However, `isConnected` is generally preferred as it's more robust and explicitly checks the connection to the document.