Check if an Element Exists with Pure JavaScript and jQuery

In this tutorial, we will learn how to check if an HTML element exists using pure JavaScript and jQuery.

 

With Pure JavaScript

The pure JavaScript solution is to get an element from the document and if it is defined do something. Let's demonstrate this with an example.

 

<div id="test"></div>

 

if (document.getElementById('test')) {
  console.log('Element exists, do something.');
}

 

With jQuery

To check whether an element exists with jQuery, use the .length property with an if statement.

 

<div id="test"></div>

 

if ($('#test').length) {
  console.log('Element exists, do something.');
}