Peter
Peter

Reputation: 11835

Jquery - How to check, if child in hidden DIV is visible?

how can i check a div in a hidden div ... if visible or not?

HTML

<div style="display:none;">
  <div id="two_child"></div>
  <div id="three_child" style="display:none"></div>
</div>

JS

if($('#two_child').is(':visible'))
{
  alert('true');
}

This will not work.

Any ideas`?

Thanks in advance! Peter

Upvotes: 9

Views: 17469

Answers (6)

Mottie
Mottie

Reputation: 86483

I've saved these two selector extensions which is essentially the same as Steve's version:

From another SO answer:

// jQuery selector to find if an element is hidden by its parent
jQuery.expr[':'].hiddenByParent = function(a) {
 return $(a).is(':hidden') && $(a).css('display') != 'none' && $(a).css('visibility') == 'visible';
};

From Remy Sharp & Paul Irish:

// reallyvisible - by remy sharp & paul irish
// :visible doesn't take in to account the parent's visiblity - 'reallyvisible' does...daft name, but does the job.
// not neccessary in 1.3.2+
$.expr[ ":" ].reallyvisible = function(a){ return !(jQuery(a).is(':hidden') || jQuery(a).parents(':hidden').length); };

Upvotes: 6

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196296

The :visible selector does not work like this

Elements can be considered hidden for several reasons:

  • They have a CSS display value of none.
  • They are form elements with type="hidden".
  • Their width and height are explicitly set to 0.
  • An ancestor element is hidden, so the element is not shown on the page.

if you want to check for css properties you can create a custom css selector as displayed in Select Element By CSS style (all with given style)

Upvotes: 4

Steve Greatrex
Steve Greatrex

Reputation: 16009

You could check the display property of the css:

if ($("#two_child").css("display") != "none") {
    //...
}

As Gaby points out in the comments, this would not work if your elements are being hidden using visibility, so you may want to extend it to:

var $child = $("#two_child");
if ($child.css("display") != "none" && $child.css("visibility") != "hidden") {
    //...
}

Upvotes: 18

BrunoLM
BrunoLM

Reputation: 100381

Use filters to check the display style, an example on jsFiddle

$("div")
.filter(function(){
    return $(this).css("display") == "none";
}).find("> div").filter(function() {
    return $(this).css("display") != "none";
}).length

Reference

Upvotes: 3

DoXicK
DoXicK

Reputation: 4812

just return false :-) An item in a box you cant find... well... you probably lost that item with the box ;-)

Upvotes: -4

kͩeͣmͮpͥ ͩ
kͩeͣmͮpͥ ͩ

Reputation: 7856

Because a child of a hidden element will always be hidden from display, you might try

$("#child_two").css("style") == "none"

This only works when you hide stuff with css though.

Upvotes: -1

Related Questions