Get Element by ID if it Exists using JavaScript

avatar

Borislav Hadzhiev

Mon Jan 03 20222 min read

Get Element by ID if it Exists using JavaScript #

Use the getElementById method to get an element by id if it exists, e.g. if (document.getElementById('my-id') !== null){}. The method returns the element whose id matches the provided string. If no element matches, null is returned.

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 1</div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript.

index.js
const el = document.getElementById('box'); console.log(el); // ๐Ÿ‘‰๏ธ div#box if (el !== null) { console.log('โœ… Element exists'); // ๐Ÿ‘‰๏ธ safe to work with element here } else { console.log('โ›”๏ธ Element does NOT exist in DOM'); }

We used the document.getElementById method to get the element whose id matches the provided string.

If no element in the DOM matches the provided string, the method returns null.

Our if block is only ran if the method did not return null.

If the getElementById returned null, the else block is ran.

You can also check if the el variable stores a truthy value, which would make your if check more implicit.

index.js
const el = document.getElementById('box'); console.log(el); // ๐Ÿ‘‰๏ธ div#box if (el) { console.log('โœ… Element exists'); } else { console.log('โ›”๏ธ Element does NOT exist in DOM'); }

In our if condition, we check if the el variable stores a truthy value.

Truthy are all values that are not falsy.

The falsy values in JavaScript are: null, undefined, 0, false, "" (empty string), NaN (not a number).

If the getElementById method returns an element, it returns a value that has a type of object, which is a truthy value, so our if block would run.

On the other side, if no element with the provided id is found, the method would return a null value, which is falsy, therefore our else block would run.

You can also check if the element exists by using a boolean value.

index.js
const elementExists = document.getElementById('box') !== null; console.log(elementExists); // ๐Ÿ‘‰๏ธ true if (elementExists) { console.log('โœ… Element exists'); } else { console.log('โ›”๏ธ Element does NOT exist in DOM'); }

The elementExists variable stores a boolean value:

  • true if the getElementById did not return a null value
  • false if the method returned null.

This approach is also easy to read and more beginner friendly, because there is no type coercion that has to happen behind the scenes - the value is already a boolean.

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