Use jQuery to check if all div's are hidden



How would I check if all the div's with class test are hidden. And if they are all hidden set wrap1 to hidden. Thanks.

<div id='wrap1'>
<div class="header">Header 1</div>
<div class='test'><a href="#">Test 1</a></div>
<div class='test'><a href="#">Test 2</a></div>
<div class='test'><a href="#">Test 3</a></div>

UPDATE: Thanks everyone for the really quick answers, I got it working. They were all very helpful.

4 个答案



  if ( $("div.test:visible").length === 0)
      $("#wrap1").hide( );


 $("#wrap1 div:visible").length == $("#wrap1 div").length
  • You need to qualify this with the appropriate class test. According to the OP the wrapper should be hidden if the “testN” classed DIVs are hidden even if the “header” DIV isn’t.

    tvanfossonAugust 03, 2009 15:28
      if ($(this).is(':hidden'))

此代码段将循环所有<div id="wrap#">,如果测试被隐藏则将其隐藏。

 $("div[id^='wrap']").each(function() {
  var wrap = $(this);

  if(wrap.children("div[class^='test']:visible").length == 0) {
  } else {;

如果您根本不想进行任何测试(如标记中的任何一项),但仍希望保持<div id="wrap#">可见,则可以使用以下修改后的代码段:

 $("div[id^='wrap']").each(function() {
  var wrap = $(this);

  if(wrap.children("div[class^='test']").length > 0 && 
     wrap.children("div[class^='test']:visible").length == 0) {
  } else {;



  • @tvanfosson: Maybe, anyway, comparing the :hidden length to the :visible length won’t work as both will return 0 if there are no elements.

    Andrew MooreAugust 03, 2009 15:29
  • @Andrew – I’m not sure. There’s a semantic difference between “there are no results” and “all of the results are hidden”. I’m not saying your answer is wrong, just pointing out that behavior applies in more than just the all are hidden case.

    tvanfossonAugust 03, 2009 15:25
  • @tvanfosson: Technically if there are no div.test in the markup, it is the same as having no div.test visible. I’m pretty sure that desired behavior.

    Andrew MooreAugust 03, 2009 15:22
  • If you only wanted the behavior when there were divs but they were all hidden, you could check to make sure the :hidden count is the same as the :visible count.

    tvanfossonAugust 03, 2009 15:23
  • Note that this would also hide the wrapper div if there were no divs with a matching class. Not sure if that’s desired behavior or not.

    tvanfossonAugust 03, 2009 15:21