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.
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.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
if ( $( "div#sample" ).length > 0 ) {
$("#output").append('div#sample is present');
} else {
$("#output").append('div#sample is not present');
}
});
</script>
</head>
<body>
<div id="sample">Sample Div</div>
<p id="output"></p>
</body>
</html>
Conclusion
In this jQuery Tutorial, we have learnt jQuery Check if HTML Element is Present() with the help of examples.