tags:

views:

47

answers:

4

Hi all,

Dont ask why but I need to add class zebra to the lis with the content next to them. I do a

$("li").each(function(index){

if(index%??? == 0) {

}

});

<ul>
<li></li>
<li></li>
<li></li> //add here class zebra
<li></li>
<li></li>
<li></li>
<li></li> //add here class zebra
<li></li>
<li></li>
<li></li>
<li></li> //add here class zebra
<li></li>
</ul>
A: 

The period is 4 so the modulo should be 4.
However it is offset by two so you need to add 2 to the index:

if ((index + 2) % 4 == 0)
Sani Huttunen
+1  A: 

From what I can tell, you want the 3rd, 7th, 11th, ... with class "zebra":

$("li").each(function(index,item){

if((index+2)%4 == 0) {
  $(item).addClass("zebra");
}

});

EDIT: Check out Andy's answer. Much better than mine :-)

Philippe Leybaert
A: 
if (index % 4 == 2)

is what I think you're looking for.

In your example, you have the 3rd, 7th and 10th elements selected.

Jamie Wong
+4  A: 

Clever selector for you; :nth-child() can accept an equation:

$('ul li:nth-child(4n+3)').addClass("zebra").text("Here");

Selects every 4th li starting at 3 onwards, :nth-child(4n-1) would also work (every 4th-1 element). No each or modulo necessary.

http://jsfiddle.net/AvPhe/ - Example based on your sample input, the zebra class is added along with the text "Hello".

Andy E
++ Much more succinct than the other answers :)
Jeriko
Thanks a lot. I didn't know about the nth-child selector. In my case though it's (4n+2)
chchrist
@chchrist: It's a cool selector :-) the example you gave in the question is (4n+3), so I just worked with that (check out the fiddle link).
Andy E
Yes you're right...
chchrist