JavaScript: How to check if an element exists in the DOM

When you need to check for the existence of a certain element in the DOM, you can use one of the following document selector methods as follows:

After you tried to retrieve the element using the selectors above, you can check if the specified element exists or not by checking the value returned by the methods.

Both querySelector() and getElementById() returns null when the element doesn’t exist, so you can check the result as follows:

if (document.getElementById("myDiv")) {
  console.log("Element exists!");
} else {
  console.log("Element DOES NOT exist!");
}

if (document.querySelector("#myDiv")) {
  console.log("Element exists!");
} else {
  console.log("Element DOES NOT exist!");
}

On the other hand, both getElementsByName() and getElementsByClassName() methods return an array, so you need to check the .length property and see if its value is greater than 0.

Here’s an example:

let elements = document.getElementsByName("paragraph");
if (elements.length) {
  console.log("At least one element exists!");
} else {
  console.log("Element DOES NOT exist!");
}

And that’s how you can check whether an element exists in the DOM or not.

Take your skills to the next level ⚡️

I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.