tags:

views:

39

answers:

3

I'm trying to figure out how I can count the number of div's inside the "bar" container then add the number as a class. For example in the first item class="bar 3" and the second class="bar 2"

<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 class="item">
  <div class="foo"></div>
  <div class="bar">
     <div class="slide"></div>
     <div class="slide"></div>
  </div>
</div><!-- /item -->
A: 
$('#item').each(function(i, elem){
    var $this = $(this),
        len = $(this).find('.bar').children('div').length;

    $this.addClass('bar ' + len);
});

While writting this I realized that you are using multiple IDs with the name item. That is no valid HTML markup and jQuery probably will only return the first occurence. Replace the ID with classes and use $('.item').

jAndy
A: 
$.each($(".item"), function(i, d) {
    var count = $(d).find(".bar div").length;
    $(d).addClass("bar_" + count);
})
Ned Batchelder
no `.count()` in jQuery. Use either `.size()` or directly `.length` property.
jAndy
oops, yup, just fixed it.
Ned Batchelder
A: 

In jQuery 1.4 you can use a function as .addClass() argument:

$('.bar').addClass(function() {
    return $(this).children('div').length;
});
David