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”.
In Chrome, this resulted in a null value being printed to the console.
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.
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!