I have this markup:
<div id="container">
<h1>Heading</h1>
<p>Some text</p>
<div class="foo">Some stuff</div>
<div class="foo">Some stuff</div>
<div class="foo">Some stuff</div>
<div class="foo">Some stuff</div>
<div class="foo">Some stuff</div>
<div class="foo">Some stuff</div>
<!-- ... same thing on down the page ... -->
<div class="foo">Some stuff</div>
<div class="foo">Some stuff</div>
<div class="foo">Some stuff</div>
</div>
I’d like to add a class to every fourth div. Here’s the jQuery that I expected would work:
$('div.foo:nth-child(4n)').addClass('bar');
But it results in:
<div id="container">
<h1>Heading</h1>
<p>Some text</p>
<div class="foo">Some stuff</div>
<div class="foo bar">Some stuff</div>
<div class="foo">Some stuff</div>
<div class="foo">Some stuff</div>
<div class="foo">Some stuff</div>
<div class="foo bar">Some stuff</div>
<div class="foo">Some stuff</div>
<div class="foo">Some stuff</div>
<div class="foo">Some stuff</div>
<div class="foo bar">Some stuff</div>
<div class="foo">Some stuff</div>
<div class="foo">Some stuff</div>
<div class="foo">Some stuff</div>
<div class="foo bar">Some stuff</div>
<div class="foo">Some stuff</div>
<div class="foo">Some stuff</div>
<div class="foo">Some stuff</div>
</div> <!-- #container -->
So, obviously all children are being counted, and only the matched element gets the class added. I could just take those other two elements into consideration and use :nth-child(4n+2), but I can’t always count on there being exactly two elements preceding my divs.
Is there an nth-child-like selector (or method) that will only take the specified element into consideration when counting?
You can use the filter function to get every 4th element as follows:
Working example @: