John Mwaniki /   29 Jul 2023

How to check if an element exists on page using jQuery

In some scenarios, you may want to programmatically check if an element exists on an HTML page in web development.

An example of such a scenario is when you may want to perform different actions or execute specific code only if a certain element exists in the HTML document.

Another instance is in error handling where you check for an element's existence before trying to manipulate it using JavaScript. This helps avoid errors and handle them gracefully with appropriate error messages or fallback actions.

You can check the existence of an element in the DOM (Document Object Model) using the jQuery length property.

The length property checks the specific element in the HTML document and returns the number of times it exists in the HTML body.

Syntax

$(elementName).length;

The elementName is the selector used to target the element. It can be the tag name (eg. "p" for <p>, "h1" for <h1>, "img" for <img>, etc), the class name (eg. ".mybtn"), or ID name (eg. "#loginForm").

The length property returns a number, which is the total number of instances of the targeted element within the page.

If the element exists in the HTML document, the returned value will be a number greater than 0. If it doesn't exist, the length property will return zero (0).

Therefore, the check involves comparing the returned value with zero. If it is greater than zero, we conclude the element exists or else it doesn't.

Example 1

if($("p").length > 0){
  // <p> exists.
  // Add your logic when it exists
}

In this example, we are checking whether the return value is larger than zero and adding our logic for its existence.

Example 2

if($("#myModal").length == 0){
  // Does not exist.
  // Add your logic for when it doesn't exist
}

In this example, we are equating the returned value to 0. If the returned value is equal to zero, then we know that it does not exist and perform our logic for when it doesn't exist.

However, a zero (0) return value evaluates to false while a value greater than 0 evaluates to true. So we can check without the use of comparison operations.

Example

if($("p").length){
  // <p> exists.
  // Logic for when it exists
}
else{
  // <p> does not exist.
  // Logic for when it doesn't exist
}

And that's it!

Checking if an element exists in the HTML document using jQuery is as simple as that.