Peter
Peter

Reputation: 1541

jquery how to hide if no more child

Initially I will have

<div id="a">
 <div id="a_1" class="toBeHide"> something </div>
 <div id="a_2" class="toBeHide"> something </div>
 <div id="a_3" class="toBeHide"> something </div>
<div>

<div id="b">
 <div id="b_1" class="toBeHide"> something </div>
<div>

I will then $('#b_1').hide(), now I would say the #b have no more child.

My question is how do detect if no more child and hide the #b ?

Upvotes: 1

Views: 72

Answers (5)

Amin Jafari
Amin Jafari

Reputation: 7207

here you go: http://jsfiddle.net/23zbU/10/

$('#b_1').hide();
var visibleCount=0;
$('#b').children().each(function(){
    if(!$(this).is(':hidden')){
        visibleCount++;
    }

    if(visibleCount==0){
        $('#b').hide();
    }
    else{
        $('#b').show();
    }
});

this code actually automates the showing and hiding of #b

Upvotes: 0

Jai
Jai

Reputation: 74738

You can use .css() method:

$('#b').css('display', function(){
   return $(this).contents().length === 0 ? 'none' : 'block';
});

Demo


Things to notice:

  1. You don't have closed the wrapper divs.
  2. use the .css() method and use the display property.
  3. return the value on count of contents length in the callback of .css()
  4. so use $(this).contents().length it will check for the textNodes too.

For #4 if your markup is something like this:

<div id="b">
    something.
</div>

Upvotes: 0

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85573

You can use like this:

   $('#b_1').hide();
if(!$('#b').children(":visible").length){
   $('#b').hide();
}

working demo

Upvotes: 0

techfoobar
techfoobar

Reputation: 66693

Since you are only hiding the children, you can check using :visible:

if($('#b > div:visible').length === 0) {
    $('#b').hide();
}

Upvotes: 3

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28513

try this : If length of children is zero then hide b_1

 $(function(){
    if($('#b_1').children().length == 0)
    $('#b_1').hide();
 });

Upvotes: 0

Related Questions