Lindsay
Lindsay

Reputation: 127

Add class depending on number of child divs

I have a parent div in which 2 to 4 child divs will be added dynamically. I need to count the child divs and then add a class to the parent div depending on the # of children.

<div id="parent">
   <div class="child">content</div>
   <div class="child">content</div>
   ...
</div>

Basically, I need to use jquery to say:

If there are 4 child divs, then add class ".four" to parent div.

If there are 3 child divs, then add class ".three" to parent div.

If there are 2 child divs, then add class ".two" to parent div.

I think I need to use .length(), but I can't figure out how to put it all together. I greatly appreciate any advice.

Thank you!

Upvotes: 0

Views: 1214

Answers (1)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382130

A way to do it :

$('#parent').removeClass().addClass(function(){
    return ["none", "one", "two", "three", "four"]
       [$(this).children('.child').length];
});

Upvotes: 2

Related Questions