Kev Kev - 2 months ago 18
jQuery Question

For each class, count elements and addClass - jQuery

I'm trying to implement a script that adds a class depending on the number of elements within a div. I have got this working but finding it hard to expand so that it runs on each class found. (Sorry for the bad wording). Example below:

jQuery

$(".flex-container").each(function() {

var numItems = $('.btn').length;

if(numItems==10||numItems==9){
$('.btn').addClass('flexten');
}else if(numItems==8||numItems==7){
$('.btn').addClass('flexeight');
}else if(numItems==6||numItems==5){
$('.btn').addClass('flexsix');
}else if(numItems==4||numItems==3){
$('.btn').addClass('flexfour');
}
});


HTML

<div class="flex-container">
<a href="#" class="btn btn-default btn-lg">Text</a>
<a href="#" class="btn btn-default btn-lg">Text</a>
<a href="#" class="btn btn-default btn-lg">Text</a>
<a href="#" class="btn btn-default btn-lg">Text</a>
</div>


The above words fine but when I attempt to add in a new div with the same class name (flex-container), the count of .btn still goes up and therefore the addClass value is not fixed per div.

Basically, I'm wanting the count to be applied per div and therefore an accurate addClass name added to each.
Hopefully this makes sense on what I'm looking to achieve.

jQuery is not my strong point so any help would be much appreciated.

Cheers

Answer

The problem is that $('.btn').length returns the total number of elements on the page with the .btn class.

Try the line below to count the number of children per div:

var numItems = $(this).children().length;

And then use this line to add a class to only the .btn child of the div selected:

$(this).children('.btn').addClass('flexfour');

I would also recommend adding an else statement to catch the scenarios where there are more or less children.

Here is a jsFiddle. Hope this helps!