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:

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:

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:

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:

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!

Facebook Comments