How to check if an element exists in JavaScript (with examples)
Tags: javascript, webdev, beginners
Published: 2023-02-06 13:41:10

> ✋ **Update:** This post was originally published on my blog [decodingweb.dev](https://www.decodingweb.dev), where you can read the [latest version](https://www.decodingweb.dev/javascript-check-if-element-exists) for a 💯 user experience. _~reza_

In JavaScript, to check if an element exists or not, you need to access it first. You can use one the following methods to access DOM elements:

- `document.getElementById()`
- `document.getElementByClassName()`
- `document.querySelector()`
- `document.querySelectorAll()`

Whenever you access a web page, the web browser parses the HTML code and populates a DOM tree of all the elements on the page. It also makes the DOM available to your JavaScript code via the DOM API. 

And the `document` object is the entry to the DOM API.

In these four methods, the first two methods return a single DOM element (Element) if the element exists. Otherwise, they return `null`.

So to check if the element exists in the DOM, you need to check the returned value.

The method `document.getElementById()` takes a case-sensitive string argument and returns the element whose `id` property matches the specified string. 

If the element doesn’t exist, we’ll get a `null` value.

```html
<html>
    <body>
        <div id=main>
            ...
        </div>

        <script>
            let element = document.getElementById('main')

            if (element !== null) {
                // Do something with the element
            }
        </script>
    </body>
</html>
```

Please note the argument you pass to `getElementById()` is case-sensitive, meaning `main` is different from `Main`.

The `document.querySelector()` method takes a CSS selector (or selectors) and returns the first element that matches the selector.

This method returns `null` if no element matches the specified selector.

Here's an example:

```html
<html>
    <body>
        <div id=main>
            <article class=post>
                <span class=post__title>
                    ...
                </span>
            </article>
        </div>

        <script>
            let element = document.querySelector('#main .post .post__title')

            if (element != null) {
                // Do something with the element
            }
        </script>
    </body>
</html>
```

## Check if an element exists in NodeList objects

Unlike the first two methods, the `document.querySelectorAll()` method returns a NodeList object.

This NodeList collection can contain zero or multiple elements that match the specified selectors. You can check the number of elements of a NodeList object via its `length` property. 

If the length is zero, it means no elements matches the selector.

```html
<html>
    <body>
        <div id=main>
            <article class=post>
                <span class=post__title>
                    ...
                </span>
            </article>
        </div>

        <script>
            let postTitles = document.querySelectorAll('#main .post .post__title')
            
            if (postTitles.length) {
                // Do something with the elements
            }
        </script>
    </body>
</html>
```

The `document.getElementByClassName()` method also returns an array-like object called an HTMLCollection. The HTMLCollection interface has a `length` property too.

You can convert both NodeList and HTMLCollection objects into arrays with `Array.from()` methods:

```js
let postTitles = document.querySelectorAll('#main .post .post__title')

postTitles = Array.from(postTitles)

if (postTitles.length) {
    // Do something with the elements
}
```

## Final notes

Always access DOM when the initial HTML document has been completely loaded and parsed. You might get unexpected results if you place your JavaScript code inside the `<head>` section.

The reason is the browser parses the document from top to bottom, and it might evaluate your JavaScript code before the elements are inserted into the DOM tree. 

It's a good practice to place your JavaScript code before the closing body tag (just like the above example). 

If you have to place your code before the body tag, you can use the **`DOMContentLoaded`** event to ensure your code only runs after the DOM content is loaded:

```html
<html>
    <head>
        <script>
            window.addEventListener('DOMContentLoaded', function () {
                let postTitles = document.querySelectorAll('#main .post .post__title')            

                if (postTitles.length) {
                    console.log('found!')
                    // Do something with the elements
                }
            })
        </script>
    </head>
    <body>
        <div id=main>
            <article class=post>
                <span class=post__title>
                    ...
                </span>
            </article>
        </div>     
    </body>
</html>
```

If you get a **ReferenceError** when accessing the document, check this [quick guide on fixing document is not defined error](https://www.decodingweb.dev/how-to-solve-referenceerror-document-is-not-defined).

Thanks for reading!

**❤️ You might like:**

- [Cannot find module error in Node.js (Fixed)](https://www.decodingweb.dev/cannot-find-module-error-in-node-js-fixed)
- [TypeError: map is not a function in JavaScript in JavaScript (Fixed)](https://www.decodingweb.dev/fix-map-is-not-a-function-error-in-javascript)
- [Add commas to numbers in JavaScript (Explained with examples)](https://www.decodingweb.dev/add-commas-to-numbers-in-javascript)
- [SyntaxError: Unexpected end of JSON input in JavaScript (Fixed)](https://www.decodingweb.dev/syntaxerror-unexpected-end-of-json-input-in-javascript)
- [How to fix "ReferenceError: document is not defined" in JavaScript](https://www.decodingweb.dev/how-to-solve-referenceerror-document-is-not-defined)