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:
document.querySelector()
document.getElementById()
document.getElementsByName()
document.getElementsByClassName()
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.