JavaScript: How to check if an element exists in the DOM
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.
More JavaScript tutorials
See allJavaScript
Sort Keys in Map Using JavaScript
Dec 11, 2023
JavaScript
Get Element by Data Attribute Using JavaScript
Dec 8, 2023
JavaScript
Convert Milliseconds to Hours Minutes Seconds in JavaScript
Dec 6, 2023
JavaScript
JavaScript Get the Index of Max Value in Array
Nov 16, 2023
JavaScript
JavaScript Check if Value is an Object
Nov 15, 2023