javascript - How do I check if an element is hidden in jQuery?

ID : 119822

viewed : 11

Tags : javascriptjquerydomvisibilityjavascript

Top 5 Answer for javascript - How do I check if an element is hidden in jQuery?

vote vote

93

Since the question refers to a single element, this code might be more suitable:

// Checks CSS content for display:[none|block], ignores visibility:[true|false] $(element).is(":visible");  // The same works with hidden $(element).is(":hidden"); 

It is the same as twernt's suggestion, but applied to a single element; and it matches the algorithm recommended in the jQuery FAQ.

We use jQuery's is() to check the selected element with another element, selector or any jQuery object. This method traverses along the DOM elements to find a match, which satisfies the passed parameter. It will return true if there is a match, otherwise return false.

vote vote

87

You can use the hidden selector:

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

And the visible selector:

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

72

if ( $(element).css('display') == 'none' || $(element).css("visibility") == "hidden"){     // 'element' is hidden } 

The above method does not consider the visibility of the parent. To consider the parent as well, you should 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 consider div2 visible while :visible not. But the above might be useful in many cases, especially when you need to find if there is any error divs visible in the hidden parent because in such conditions :visible will not work.

vote vote

63

None of these answers address what I understand to be the question, which is what I was searching for, "How do I handle items that have visibility: hidden?". Neither :visible nor :hidden will handle this, as they are both looking for display per the documentation. As far as I could determine, there is no selector to handle CSS visibility. Here is how I resolved it (standard jQuery selectors, there may be a more condensed syntax):

$(".item").each(function() {     if ($(this).css("visibility") == "hidden") {         // handle non visible state     } else {         // handle visible state     } }); 
vote vote

53

From How do I determine the state of a toggled element?


You can determine whether an element is collapsed or not by using the :visible and :hidden selectors.

var isVisible = $('#myDiv').is(':visible'); var isHidden = $('#myDiv').is(':hidden'); 

If you're simply acting on an element based on its visibility, you can just include :visible or :hidden in the selector expression. For example:

 $('#myDiv:visible').animate({left: '+=200px'}, 'slow'); 

Top 3 video Explaining javascript - How do I check if an element is hidden in jQuery?

Related QUESTION?