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.
HTML<div id="my-element"></div>
JAVASCRIPTconst element = document.getElementById("my-element");
if (element) {
console.log("Element exists");
} else {
console.log("Element does not exist");
}
BASHElement 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.
HTML<p>A paragraph</p>
<p>A paragraph</p>
<p>A paragraph</p>
JAVASCRIPTconst elements = document.getElementsByTagName("p");
if (elements.length > 0) {
console.log("Elements exists");
} else {
console.log("Elements do not exist");
}
BASHElements 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.
HTML<div class="my-class"></div>
<div class="my-class"></div>
<div class="my-class"></div>
JAVASCRIPTconst elements = document.getElementsByClassName("my-class");
if (elements.length > 0) {
console.log("Elements exists");
} else {
console.log("Elements do not exist");
}
BASHElements 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.
HTML<div class="my-class"></div>
<div class="my-class"></div>
<div class="my-class"></div>
JAVASCRIPTconst element = document.querySelector(".my-class");
if (element) {
console.log("Element exists");
} else {
console.log("Element does not exist");
}
BASHElement 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!
How to Install Node on Windows, macOS and Linux
Getting Started with Solid
Getting Started with Electron
Git Tutorial: Learn how to use Version Control
How to Set Up Cron Jobs in Linux
How to deploy a PHP app using Docker
How to deploy a Node app using Docker
Getting Started with Handlebars.js
Getting User Location using JavaScript's Geolocation API
Getting Started with Vuex: Managing State in Vue
How To Create a Modal Popup Box with CSS and JavaScript
Getting Started with Moon.js
