jQuery Check if HTML Element is Present

Using jQuery there are many ways to check if a HTML Element is present or not. In this tutorial, we shall look into some of the ways with examples.

To check if an element is present in jQuery, use jQuery Selector on the element and .length property. If there is at least one element for the given selection criteria, then the length property returns an integer that is greater than zero.

if( $( "element" ).length > 0 ){
  // element is present
  // your javascript code here
}

If specified element is not present, then the length property on the jQuery selection returns zero.

Examples – jQuery Check if HTML Element is Present

The following examples help you understand how to check if HTML Element is present using jQuery.

ADVERTISEMENT

1. Example – Check if HTML Element is Present

In the following example, we shall check if there is a div element with id=”sample”. We will use an if-else statement to print a message to output paragraph.

Conclusion

In this jQuery Tutorial, we have learnt jQuery Check if HTML Element is Present() with the help of examples.