Count total children divs inside a container

Posted by kuswantin on Stack Overflow See other posts from Stack Overflow or by kuswantin
Published on 2010-04-21T05:47:25Z Indexed on 2010/04/21 5:53 UTC
Read the original article Hit count: 282

Filed under:
|

I want to count the total divs inside a container and toggle their visibilities with structure like this. Please also note that the div.content may also reside inside another nested or even nested-nested containers. That's why I handle it with jquery to add div.topmost for each topmost parent container:

<div id="parent">
  <div class="counter">There are 3 div.contents inside the container below</div>
  <div class="container">
    <div class="content"> 1 </div>
    <div class="container"> <!--container inside container -->
      <div class="content"> 2 </div>
      <div class="content"> 3 </div>
    </div>
  </div>

  <div class="counter">There are 5 div.contents inside the container below</div>
  <div class="container">
    <div class="content"> 1 </div>
    <div class="content"> 2 </div>
    <div class="content"> 3 </div>
    <div class="content"> 4 </div>
    <div class="content"> 5 </div>
  </div>
</div>

And the jquery:

  // only grab the top most container
  $('#parent > .container').addClass('topmost');
    var topMost = $(".topmost");
    var totContent = topMost.children('.content').size();

    if (topMost.length > 0) {
      topMost.before('<div class="toggle">There are ' + totContent + ' div.contents inside the container below</div>');
    }

   topMost.hide();

  $('#parent > .counter').click(function() {
    $(this).next('.topmost').toggle();
    //alert(totContent);
     return false;
  });

But I can't make it work to loop for each div.counter. The counter always shows all div.content. So placing the each function is suspected to be the problem.

Any hep would be very much appreciated.

Thanks

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about count