views:

856

answers:

2
+2  Q: 

addClass every nth

I have a list of elements that I want to style in 3 different ways.

I want every 3rd list item to have the same class throughout the whole list.

For example:

<li class="A">Some Content</li>
<li class="B">Some Content</li>
<li class="C">Some Content</li>
<li class="A">Some Content</li>
<li class="B">Some Content</li>
<li class="C">Some Content</li>
<li class="A">Some Content</li>
<li class="B">Some Content</li>
<li class="C">Some Content</li>

I can do 2 with :odd/even, but how to do it with 3?

A: 

I recommend something like this:

var i = 0;
$("li").each(function() {
    var newClass = 'A';
    if (i % 3 == 1) newClass = 'B';
    if (i % 3 == 2) newClass = 'C';
    $(this).addClass(newClass);
});
VoteyDisciple
+12  A: 

try

$("ul li:nth-child(3n+1)").addClass("A")
$("ul li:nth-child(3n+2)").addClass("B")
$("ul li:nth-child(3n)").addClass("C")

Feel free to consolidate it to make it prettier, but I wanted to expose the selectors.

Marc
To make this a working solution use: $('ul li:nth-child(3n)').addClass('every-third-item-class');
brownstone
@brownstone - see the edit, I changed it to address his total concern (albeit longhanded)
Marc
Thanks Marc. This was exactly what I wanted.
davebowker
@Marc - To be honest I was just being picky about the missing single-quotes :) although pointing out the +n notation makes the answer complete.
brownstone
@brownstone - woops! good eye, missed those. @davebowker - glad I could help
Marc