I have a list of <li> elements, and I’m using :nth-child to target specific children of every 3rd and 4th element, and give them an additional class .right.
But, when I hide some elements (let’s say, the first or second list item), it doesn’t work properly. I want to add class “right” only to children of visible list items. How can I do that?
This is the code I’m using:
$(".ilist:visible:nth-child(4n+3)").find(".window").addClass("right");
$(".ilist:visible:nth-child(4n+4)").find(".window").addClass("right");
And I remove all classes .right with this:
$(".ilist .window.right").removeClass("right");
HTML structure:
<ul>
<li class="ilist">
...
<div class="name">Name (Search works with it)</div>
<div class="window"></div>
</li>
...
</ul>
The fact that you hide an element does not change its position in the DOM tree, so
nth-child(4n+3)won’t change if you hide any sibling list item.When you toggle the visibility some elements list items, you’ll have to reset your
rightclasses, and reapply to the appropriate elements.You can do that by passing a function to
addClass, instead of the new class name. This function will receive the index of the matched element as the first parameter, and you can use it to check if it’s the 3rd or 4th. If it is, return the new class name you want to apply:Live demo at http://jsfiddle.net/6TMmJ/