Check if an Element does not exist in the DOM using JS

avatar

Borislav Hadzhiev

Sun Jan 09 20222 min read

banner

Photo by Chad Madden

Check if an Element does not exist in the DOM using JS #

To check if an element does not exist in the DOM:

  1. Use the getElementById or querySelector methods to select the element.
  2. Check if the stored value is equal to null.
  3. If the value is equal to null, the element does not exist in the DOM.

Here is the HTML for the examples in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box">Box content</div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
// โœ… Using getElementById const el1 = document.getElementById('does-not-exist'); if (el1 === null) { console.log('element does NOT exist in DOM'); } else { console.log('element exists in DOM'); } // โœ… Using querySelector const el2 = document.querySelector('.my-class'); if (el2 === null) { console.log('element does NOT exist in DOM'); } else { console.log('element exists in DOM'); }

In our first example, we used the document.getElementById method to select an element by id.

The method returns the element, whose id property matches the provided string.

If no element with the provided id exists in the document, a null value is returned.

Our if statement checks if the value stored in the el1 variable is equal to null.

If if block is only ran if the element does not exist in the DOM, otherwise the else block is ran.

In the second example we used the document.querySelector method to get the first element that matches the provided selector.

index.js
const el2 = document.querySelector('.my-class'); if (el2 === null) { console.log('element does not exist in DOM'); } else { console.log('element exists in DOM'); }

The querySelector method takes a string that represents a valid CSS selector as a parameter.

If no elements match the selector, the method returns a null value just like the getElementById method.

Since there are no elements with a class of my-class on the page, the el2 variable stores a null value and the if block is ran.

You can also provide multiple, comma-separated selectors to the querySelector method.

index.js
const el2 = document.querySelector('.my-class, #my-id'); if (el2 === null) { console.log('element does not exist in DOM'); } else { console.log('element exists in DOM'); }

The example above tries to select an element with a class of my-class or an id set to my-id.

If neither element is found, the querySelector method returns null.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee