jQuery Check if element is hidden
Using jQuery there are many ways to check if a HTML Element is hidden or not. In this tutorial, we shall look into some of the ways with examples.To check if an element is hidden in jQuery, there are two ways :
1. Use jQuery Selector on the element and :hidden value.
if( $( "element:hidden" ).length ){
}
2. Get the CSS display attribute of the element and check if it is ‘none’.
if( $(" element ").css("display") == "none" ){
}
Examples – jQuery Check if element is hidden
The following examples help you understand how to check if an element is hidden using jQuery.
1. Example – Check if HTML Element is hidden
In the following example, paragraph with id=”pa” has display style attribute set to none. We shall check if the element is hidden using jQuery.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
if($("p#pa:hidden").length){
alert("The element is hidden");
}
});
</script>
</head>
<body>
<div style="display:visible;">
<p id="pa" style="display:none;">A paragraph.</p>
</div>
<p id="pb">Another paragraph.</p>
</body>
</html>
2. Example – Check if HTML Element or any of its ancestors are hidden
In the following example, paragraph with id=”pa” has display style attribute set to block. But its parent (DIV) is hidden. We shall check if the element is hidden using jQuery.
<!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($("p#pa:hidden").length){
alert("The element is hidden");
}
});
</script>
</head>
<body>
<div style="display:none;">
<p id="pa">A paragraph.</p>
</div>
<p id="pb">Another paragraph.</p>
</body>
</html>
3. Example – Using CSS display attribute, check if element is hidden
In the following example, we use CSS display attribute value. If the value is ‘none’, then the element is hidden.
<!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($( "p#pa" ).css("display") == "none"){
alert("The element is hidden");
}
});
</script>
</head>
<body>
<p id="pa" style="display:none;">A paragraph.</p>
<p id="pb">Another paragraph.</p>
</body>
</html>
Conclusion
In this jQuery Tutorial, we have learnt how to check if an element is hidden using jQuery, with the help of examples.