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

Following examples help you understand the usage of jQuery Check if element is hidden :

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>
Try Online

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>
Try Online

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>
Try Online

Conclusion

In this jQuery Tutorial, we have learnt jQuery Check if element is hidden() with the help of examples.