How to check if an element is attached to the DOM using JavaScript?

Published February 8, 2021

To check if an element is connected or attached to the DOM or the document object ( or otherwise called the context), you can use the isConnected property in the element's object in JavaScript.

// Check if an element is attached to DOM
console.log(h1Tag.isConnected); // true
  • The isConnected element property returns boolean true if it connected to the DOM (document object) and false if not.

To understand it better let's first make an h1 tag using the createElement() method available in the global document object like this,

// Make a custom h1 tag
const myh1Tag = document.createElement("h1");

Now let's check to see the value of the isConnected property in the myh1Tag.

// Make a custom h1 tag
const myh1Tag = document.createElement("h1");

// Check the value of isConnected
console.log(myh1Tag.isConnected); // false

As you can see that the isConnected property returns boolean false because this is not connected to the DOM yet.

Now let's append the myh1Tag to the DOM using the appendChild() method available in the document.body object and check the value again like this,

// Make a custom h1 tag
const myh1Tag = document.createElement("h1");

// Check the value of isConnected
console.log(myh1Tag.isConnected); // false

// Append myh1Tag to DOM
document.body.appendChild(myh1Tag);

// Check the value of isConnected
// to see if the element is attached to DOM
console.log(myh1Tag.isConnected); // true

Now the property returns boolean true because it is attached to the DOM.

See the above example live in JSBin.

Feel free to share if you found this useful 😃.


Share on: Facebook Twitter