How to Check if a DOM element exists using JavaScript

Updated onbyAlan Morel
How to Check if a DOM element exists using JavaScript

The DOM, standing for Document Object Model, is a tree-like structure that represents the HTML document.

With the rise of front-end libraries like React, Vue, and Angular, it can sometimes be difficult to determine if a DOM element exists.

In this post, we'll look at all the ways to check if an element exists in the DOM using JavaScript.

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

There are a few ways to check if an element exists in the DOM using JavaScript.

The first one is maybe the most common one, document.getElementById().

This method takes an id and returns the element with that id, or null if it doesn't exist.

<div id="my-element"></div>
const element = document.getElementById("my-element");

if (element) {
    console.log("Element exists");
} else {
    console.log("Element does not exist");
}
Element exists

If you want to use the name of the tag, you can use document.getElementsByTagName(), which returns a list of elements with that tag name.

<p>A paragraph</p>
<p>A paragraph</p>
<p>A paragraph</p>
const elements = document.getElementsByTagName("p");

if (elements.length > 0) {
    console.log("Elements exists");
} else {
    console.log("Elements do not exist");
}
Elements exists

If you want to get elements by a class, you can use document.getElementsByClassName(), which returns a list of elements with that class name.

<div class="my-class"></div>
<div class="my-class"></div>
<div class="my-class"></div>
const elements = document.getElementsByClassName("my-class");

if (elements.length > 0) {
    console.log("Elements exists");
} else {
    console.log("Elements do not exist");
}
Elements exists

Finally, you can alternatively use the versatile document.querySelector() method, which returns the first element that matches the selector.

In this method, you can pass in an ID, class, tag, or any combination.

<div class="my-class"></div>
<div class="my-class"></div>
<div class="my-class"></div>
const element = document.querySelector(".my-class");

if (element) {
    console.log("Element exists");
} else {
    console.log("Element does not exist");
}
Element exists

Conclusion

In this post, we learned how to check if an element exists in the DOM using JavaScript.

We looked at the document.getElementById(), document.getElementsByTagName(), document.getElementsByClassName(), and document.querySelector() methods, all with different valid use cases.

Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.