How can I add a class to every 4th - 1 element?

◇◆丶佛笑我妖孽 提交于 2019-12-05 19:32:51

The :nth-child() selector can accept an equation, and it solves your problem perfectly:

$('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 "Here".

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 :-)

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)
if (index % 4 == 2)

is what I think you're looking for.

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!