9

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

Peter
  • 11,413
  • 31
  • 100
  • 152
  • 6
    How can a child in a hidden div be visible? – rahul Nov 03 '10 at 12:33
  • 5
    I think there's some confusion here, it's *not* visible, since it isn't dislayed....because a parent being hidden means it's hidden as well. `:visible` doesn't mean `display != "none"`, it means *is it visible* (does it have dimensions?), and it's not. – Nick Craver Nov 03 '10 at 12:34
  • From the point of view of user of the web page, the child will be invisible, but what status is returned by `is(':visible')`? Does it return the implicit or explicit visibility? – belugabob Nov 03 '10 at 12:35
  • All children in an element that has `display:none` will be hidden. But I think that Peter wants to know what it's own display-property is. But I can't think of a reason why you want to know that... The answer of Steve Greatrex should get what you want anyway. – Justus Romijn Nov 03 '10 at 12:41
  • Visible checks for visibility of the element, not just the `display` style. See my answer on how to filter the selection using `.filter()`, then you can check the style. – BrunoLM Nov 03 '10 at 13:02

6 Answers6

18

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") {
    //...
}
Steve Greatrex
  • 15,789
  • 5
  • 59
  • 73
  • 3
    @David - He's checking `!= "none"`, *any* other display type would be valid. – Nick Craver Nov 03 '10 at 12:36
  • sorry, I meant what if display == '' ? does jQuery automatically replace '' with none? – kͩeͣmͮpͥ ͩ Nov 03 '10 at 12:39
  • @David - `""` dos display will be the default for the element, for a `
    ` it's `block`, for a `
  • ` it's `list-item`, etc.
– Nick Craver Nov 03 '10 at 12:40
  • it would fail for `visibility:hidden` – Gabriele Petrioli Nov 03 '10 at 12:45
  • @Gaby - it depends on your definition of "visible", `visibility: hidden` still occupies space in the page, so it is something you can see. – Nick Craver Nov 03 '10 at 13:27
  • @nick, i agree that it depends.. but in the same manner, an ancestor `display:none` means all children are invisible (*as jquery supports*). I was only offering an additional case to watch for, since the OP is unclear on what he wants exactly.. – Gabriele Petrioli Nov 03 '10 at 13:35