user991830 user991830 - 6 months ago 12
Javascript Question

jQuery addClass to every other html div class

I have a list of blog items (could be 10+) - see JSfiddle which demo's just 4 items.

I am using Bootstrap and want to dynamically add a 'container' class to the 2nd, 4th, 6th, etc with jQuery - every other

<div class="item">
- so that I end up with the following:

<div class="blog">
<div class="item">
<img src="http://dummyimage.com/1300x200/000000/fff" class="img-responsive" />
</div>
<div class="item container">
<img src="http://dummyimage.com/1300x200/000000/fff" class="img-responsive" />
</div>
<div class="item">
<img src="http://dummyimage.com/1300x200/000000/fff" class="img-responsive" />
</div>
<div class="item container">
<img src="http://dummyimage.com/1300x200/000000/fff" class="img-responsive" />
</div>
</div>


How would I do this using the jQuery addClass ?

Answer

Try this:

$(".item:nth-child(even)").addClass("container");

https://jsfiddle.net/kqr3o56r/