How to check if element is hidden in jQuery

You can toggle the visibility of an element using the .hide(), .show(), or .toggle() functions. How would you test if the element is visible or hidden?

Solution 1:

Since the question is about one element, this code might be more appropriate:
// Checks css for display:none, ignores visibility:false
$(element).is(":visible"); 
 
// The same works with hidden
$(element).is(":hidden");

Solution 2:

You can use hidden selector
// Matches all elements that are hidden
$('element:hidden')
And visible selector

// Matches all elements that are visible
$('element:visible')

Solution 3:

if ( $(element).css('display') == 'none' || $(element).css("visibility") == "hidden"){
    // element is hidden
}
if ( $(element).css('display') == 'none' || $(element).css("visibility") == "hidden"){
    // element is hidden
}
The above method does not respect the visibility of the parent. To view the parent too, you must use .is(": hidden") or .is(": visible") For example,
<div id="div1" style="display:none">
  <div id="div2" style="display:block">Div2</div>;
</div>
The above method will assume div2 is visible but :visible is not. But the above can be useful in many cases, especially when you need to figure out if there are any div errors visible in the hidden parent, because under such conditions :visible won’t work.
Popular articles