Heading

Some text

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
source share
4 answers

You can use the filter function to get every 4th element as follows:

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

@:

http://jsfiddle.net/wCxSv/

+12

jQuery 1.9+ :nth-of-type .

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

: : nth-of-type vs: nth-child

+1

:

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

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

, (%) , (.. , .) . - .

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

Source: https://habr.com/ru/post/1792271/


All Articles