Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery detect visible but hidden elements

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.

like image 609
Paul Avatar asked Mar 31 '10 14:03

Paul


People also ask

How check element is hidden or not in jQuery?

Answer: Use the jQuery :visible Selector You can use the jQuery :visible selector to check whether an element is visible in the layout or not. This selector will also select the elements with visibility: hidden; or opacity: 0; , because they preserve space in the layout even they are not visible to the eye.

How do I get only visible elements in jQuery?

Answer: Use the jQuery :visible and :hidden Selector You can simply use the jQuery :visible or :hidden selector to select all the visible or hidden elements in an HTML page. The jQuery :visible selector considered an element visible if they consume space in the document.

How do you know if an element is hidden or not?

To check if an element is hidden or not, jQuery :hidden selector can be used. .toggle() function is used to toggle the visibility of an element. Click!

Is visible opposite in jQuery?

The :hidden selector is the opposite of the :visible selector.


1 Answers

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';
}
like image 74
Nick Craver Avatar answered Nov 15 '22 13:11

Nick Craver