Sometimes, we want to check if a div does not exist with JavaScript.
In this article, we’ll look at how to check if a div does not exist with JavaScript.
How to check if a div does not exist with JavaScript?
To check if a div does not exist with JavaScript, we can check if null
is returned when we try to select an element.
For instance, we write
if (!document.getElementById("given-id")) {
//...
}
to check if getElementById
returns null
when we try to select an element by its ID.
If it does, then the element with the ID doesn’t exist.
Conclusion
To check if a div does not exist with JavaScript, we can check if null
is returned when we try to select an element.