How to select every nth part of a child in jQuery?
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 would like to add a class to every fourth div. Here the jQuery I expected would work:
$('div.foo:nth-child(4n)').addClass('bar');
But this leads to:
<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, it is obvious that all children are counted, and only the corresponding element receives the added class. I could just look at these two other elements and use :nth-child(4n+2), but I can’t always count on divexactly two elements in front of my s.
Is there an nth-child-like selector (or method) that only considers the specified element when counting?
+3
4 answers
http://api.jquery.com/filter/#using-filter-function . .
, (%) , (.. , .) . - .
$('div.foo').each(function(index) {
if((index+1)%4 == 0){
$(this).addClass('bar');
});
0