How to check if an element exists in JavaScript (with examples)

Updated Sep 22, 2023 ⤳ 4 min read

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:

🎧 Debugging Jam

Calling all coders in need of a rhythm boost! Tune in to our 24/7 Lofi Coding Radio on YouTube, and let's code to the beat – subscribe for the ultimate coding groove!" Let the bug-hunting begin! 🎵💻🚀

  1. document.getElementById()
  2. document.getElementByClassName()
  3. document.querySelector()
  4. 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>
    <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>
    <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>
    <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:


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. 

Additionally, 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>
    <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.

I hope these examples simplified the "javascript check if the element exists" problem for you.

Thanks for reading!

Disclaimer: This post may contain affiliate links. I might receive a commission if a purchase is made. However, it doesn’t change the cost you’ll pay.

`
Exit mobile version