Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

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

like image 918
Peter Avatar asked Nov 03 '10 12:11

Peter


4 Answers

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") {
    //...
}
like image 177
Steve Greatrex Avatar answered Nov 14 '22 22:11

Steve Greatrex


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); };
like image 36
Mottie Avatar answered Nov 14 '22 21:11

Mottie


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)

like image 4
Gabriele Petrioli Avatar answered Nov 14 '22 22:11

Gabriele Petrioli


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

  • jQuery .filter()
like image 3
BrunoLM Avatar answered Nov 14 '22 22:11

BrunoLM