Categories
JavaScript Answers

How to check if a div does not exist with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *