开发者

jquery nth child that is currently visible

I can style every 4th 'item' div like so

  jQuery(".item:nth-child(4n)").addClass("fourth-item");

and that works fine, but then I hide some items, show some others and want to re-do this styling, but only styling every 4th item that is visible. So I have a function that will remove this styling and reapply it, but I need to specify in the reapplying of the style that it is only every 4th visible item, not every 4th item. I know the ":visible" selector but can't seen to 开发者_StackOverflow社区chain it with the nth-child selector properly, any ideas?

I've tried various things like this to no avail...

jQuery(".item").removeClass("fourth-item");
jQuery(".item:visible:nth-child(4n)").addClass("fourth-item");


:nth-child scans the children of the parent no matter what their styling is. The counting in :nth-child is relative to the parent element, not the previous selector. This is explained in the jQuery docs for :nth-child:

With :nth-child(n), all children are counted, regardless of what they are, and the specified element is selected only if it matches the selector attached to the pseudo-class.

Using a more simple method with each does exactly what you want:

$('#test li:visible').each(function (i) {
    if (i % 4 == 0) $(this).addClass('fourth-item');
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜