const elements = document.getElementsByTagName("p");
if (elements.length > 0) {
console.log("Elements exists");
} else {
console.log("Elements do not exist");
}
BASH
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.
const elements = document.getElementsByClassName("my-class");
if (elements.length > 0) {
console.log("Elements exists");
} else {
console.log("Elements do not exist");
}
BASH
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.
const element = document.querySelector(".my-class");
if (element) {
console.log("Element exists");
} else {
console.log("Element does not exist");
}
BASH
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!