开发者

How do I select every nth of a specific child element 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'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 s开发者_StackOverflowtuff</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:

$('div.foo').filter(function(index){
 return (index%4 == 3);
}).addClass('bar');

Working example @:

http://jsfiddle.net/wCxSv/


In jQuery 1.9+ :nth-of-type would work here.

$('div.foo:nth-of-type(4n)').addClass('bar');

Reference: A good description of :nth-of-type vs :nth-child


You could always do it yourself:

$('div.foo').each( function(i) {
  if( i % 4 != 3 )
    return
  $(this).addClass('bar')
})


http://api.jquery.com/filter/#using-filter-function Great tutorial. On using filter.

The basic idea is to use the modulus operator (%) in combination with each or filter to iterate over the elements and only apply actions when the modulus returns no remainder (ie, the index of the iteration is a multiple that you desire.) This is a common practice in a lot of contexts. You can also do something similar with the each function.

$('div.foo').each(function(index) {
  if((index+1)%4 == 0){
    $(this).addClass('bar');
 });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜