Check if HTML element exists using JavaScript.

In this guide, I will show you how to check if a given HTML element exists using JavaScript. For the sake of people who are not using jQuery, I will also include a vanilla JavaScript example.

Without jQuery.

If you are not using the jQuery library, then you can use the following JavaScript code:

<div id="test">Example DIV element.</div>

<script>
    //Attempt to get the element using document.getElementById
    var element = document.getElementById("test");

    //If it isn't "undefined" and it isn't "null", then it exists.
    if(typeof(element) != 'undefined' && element != null){
        alert('Element exists!');
    } else{
        alert('Element does not exist!');
    }
</script>

In the code above, we used vanilla JavaScript to check if an element called “test” exists or not. If you run this code on your local machine, you will find that it detects the existence of our example DIV element.

This code attempts to retrieve the Element object that represents our “test” DIV by using the Document methodĀ getElementById(). If no element with the ID “test” can be found, then the method will return “null” / “undefined”.

To test this out for yourself, you can try the following JavaScript:

var example = document.getElementById("does-not-exit");
console.log(example);

In Chrome, this resulted in a null value being printed to the console.

Node.contains()

TheĀ Node.contains() method is another solution that is supported across almost every browser. An example of this method being used:

<div id="test">Example DIV element.</div>
<script>
    //Using document.body.contains.
    if(document.body.contains(document.getElementById('test'))){
        alert('Element exists!');
    } else{
        alert('Element does not exist!');
    }
</script>

As you can see above, this method requires a node, which we supplied by using the document.getElementById() method.

Using jQuery.

If you are using jQuery, then you can use the length attribute. Let’s take our example above an modify it to use the jQuery library instead:

<div id="test">Example DIV element.</div>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
    //If the length attribute of the element is not 0, then it exists.
    if($('#test').length > 0){
        alert('Element exists!');
    } else{
        alert('Element does not exist!');
    }
</script>

As you can see, with jQuery, it is even simpler to check if an element exists or not. If the length attribute of an element object is 0, then it does not exist.

If you run the snippet above, you should see an alert dialog saying “Element exists!”

Hopefully, you found this guide to be useful!