jQuery detect visible but hidden elements

Paul picture Paul · Mar 31, 2010 · Viewed 13.4k times · Source

This seems like it should be fairly easy - but I can't find the right selector for it

According to the docs (http://api.jquery.com/hidden-selector/ and http://api.jquery.com/visible-selector/)...

Elements can be considered hidden for several reasons:

An ancestor element is hidden, so the element is not shown on the page.

What I want to detect is "this element is visible, but is contained in a hidden parent". Ie, if I made the parent visible, this element would also be visible.

Answer

Nick Craver picture Nick Craver · Mar 31, 2010

If this is something you'll commonly use, make your own selector :) Here's an example:

jQuery.expr[':'].hiddenByParent = function(a) { 
   return jQuery(a).is(':hidden') && jQuery(a).css('display') != 'none'; 
};

You can use it like this, test markup:

<div style="display: none" id="parent">
  <div>
      <div id="child">Test</div>
  </div>
</div>
​

Examples of use:

$("div:hiddenByParent").length;​​​​​​​​​​​​​​​​​​ // "2" (plain div + child match)
$("#child").is(":hiddenByParent"); // true

Alternatively, you can use the .filter() function like this:

$('selector').filter(function() {
  return $(this).is(':hidden') && $(this).css('display') != 'none';
}