tags:

views:

38

answers:

1

How can I count the number of divs with the class of "slide" in each set. In the example below the first group "item" will and up with three and the second group will have two. I've been trying to use .length but it adds all of the "slide" divs up.

<div class="item">
  <div class="foo"></div>
  <div class="bar">
     <div class="slide"></div>
     <div class="slide"></div>
     <div class="slide"></div>
  </div>
</div><!-- /item -->

<div id="item">
  <div class="foo"></div>
  <div class="bar">
     <div class="slide"></div>
     <div class="slide"></div>
  </div>
</div><!-- /item -->
+3  A: 

This will get you an array of the counts of .slide divs within each .item, using .map:

var counts = $(".item").map(function() {
    return $(this).find(".slide").length;
}).get();

Try it here. In your markup, the second 'item' div has the ID 'item' instead of the class name. I changed it for the demo. Alternatively, you could just use the selector .bar instead of .item in the above solution, and the result will still be the same.

karim79
instead of an array is there a way the number could be added to the class of .bar like class="bar 3" and class="bar 2"
Alex
+1 for map(). Great feature, underused.
Ken Redler