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

Here's how you can check if a certain element exists in the DOM

Posted on April 21, 2021


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.

Related articles:

Grab the free JavaScript book today 👍

Learn the building blocks of JavaScript programming language like data types, functions, objects, arrays and classes.

Use the knowledge from the book to build a small but solid program.

Learn more