jquery nth child that is currently visible

前端 未结 1 1863
情话喂你
情话喂你 2020-11-29 08:50

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

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

and that works fine, but then I hid

相关标签:
1条回答
  • 2020-11-29 09:10

    :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 讨论(0)
提交回复
热议问题