How to Check if an Element Is Hidden in jQuery

Sundeep Dawadi Feb 02, 2024
  1. Method to Check if an Element Is Hidden in jQuery
  2. Understand the :hidden Selector in jQuery
  3. Quick Tips to Check Whether an Element Is Hidden
How to Check if an Element Is Hidden in jQuery

Any object in DOM can be hidden by assigning its CSS property of display as none.

Method to Check if an Element Is Hidden in jQuery

First, we create a heading element <h1> and apply inline CSS property to hide it.

<h1 style="display:none;">Your text here</h1>

In jQuery there are two visibility filters - :hidden and :visible selectors. They specify if the element is hidden and visible, respectively. It can be easily checked by the following method.

<script>
$(document).ready(function(){
//checks if document is ready
 if($("h1").is(":hidden")){
  alert("The heading is hidden.");
  //your function here
 } 
if($("h1").is(":visible"){
  alert("The heading  is visible.");
 }
});
</script>

It gives an alert saying, The heading is hidden.

Note
If you place multiple elements with one being hidden and another being visible , it triggers both is(":visible") and is(":hidden").

Understand the :hidden Selector in jQuery

The :hidden selector identifies an element as hidden for the following reasons:

  1. It has CSS display property with a value of none.
  2. The element is a form element with type="hidden".
  3. The height and width values of the element is set explicitly to 0.
  4. The parent element is hidden.

So, elements with CSS visibility property set to hidden or opacity property to 0 are considered visible in jQuery as they still consume space in the DOM.

Alternatively, to check the specific CSS property of the element to check if it is hidden, we can use the following method.

<script>
if ( $(h1).css('display') == 'none' || $(h1).css('opacity') == '0'){
alert("The heading is hidden.");
//your function here
}
</script>

Quick Tips to Check Whether an Element Is Hidden

jQuery cannot take advantage of the native DOM querySelectorAll() method. It also creates some performance issues as it forces the browser to re-render the page to determine visibility. So rather than using elements, you can use classes or CSS selectors and then use .find(":hidden").

<h1 style="display:none;">Your text here</h1>
<script>
 $(document).ready(function(){
  var hiddenHeadings = $("body").find(":hidden").is("h1");
   if(hiddenHeadings.length > 0){
    alert("There is atleast one heading hidden.");
   }
 });
</script>

Here the hiddenHeadings can be directly accessed and can be operated upon.