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
- Managing PHP Dependencies with Composer
- Getting Started with Express
- Create an RSS Reader in Node
- How to deploy a Deno app using Docker
- How to deploy an Express app using Docker
- How to deploy a Node app using Docker
- How to Scrape the Web using Node.js and Puppeteer
- Learn how to build a Slack Bot using Node.js
- Creating a Twitter bot with Node.js
- Building a Real-Time Note-Taking App with Vue and Firebase
- Setting Up a Local Web Server using Node.js