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 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");
In order for the nth-child rules you've declared to work after a user clicks to hide divs, you need to remove the hidden divs from the DOM, so they no longer exist as siblings.
jQuery :nth-child() Selector The :nth-child(n) selector selects all elements that are the nth child, regardless of type, of their parent. Tip: Use the :nth-of-type() selector to select all elements that are the nth child, of a particular type, of their parent.
As a general rule, if you want to select an interval of a selector regardless of the type of element it is, use nth-child . However, if you want to select a specific type only and apply an interval selection from there, use nth-of-type .
To get the nth-child of an element using the querySelector method, pass the :nth-child() pseudo-class as a parameter to the method, e.g. document. querySelector('#parent :nth-child(1)') . The nth-child pseudo-class returns the element that matches the specified position.
: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');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With