Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I select every nth of a specific child element in jQuery?
    text
    copied!<p>I have this markup:</p> <pre><code>&lt;div id="container"&gt; &lt;h1&gt;Heading&lt;/h1&gt; &lt;p&gt;Some text&lt;/p&gt; &lt;div class="foo"&gt;Some stuff&lt;/div&gt; &lt;div class="foo"&gt;Some stuff&lt;/div&gt; &lt;div class="foo"&gt;Some stuff&lt;/div&gt; &lt;div class="foo"&gt;Some stuff&lt;/div&gt; &lt;div class="foo"&gt;Some stuff&lt;/div&gt; &lt;div class="foo"&gt;Some stuff&lt;/div&gt; &lt;!-- ... same thing on down the page ... --&gt; &lt;div class="foo"&gt;Some stuff&lt;/div&gt; &lt;div class="foo"&gt;Some stuff&lt;/div&gt; &lt;div class="foo"&gt;Some stuff&lt;/div&gt; &lt;/div&gt; </code></pre> <p>I'd like to add a class to every fourth div. Here's the jQuery that I expected would work:</p> <pre><code>$('div.foo:nth-child(4n)').addClass('bar'); </code></pre> <p>But it results in:</p> <pre><code>&lt;div id="container"&gt; &lt;h1&gt;Heading&lt;/h1&gt; &lt;p&gt;Some text&lt;/p&gt; &lt;div class="foo"&gt;Some stuff&lt;/div&gt; &lt;div class="foo bar"&gt;Some stuff&lt;/div&gt; &lt;div class="foo"&gt;Some stuff&lt;/div&gt; &lt;div class="foo"&gt;Some stuff&lt;/div&gt; &lt;div class="foo"&gt;Some stuff&lt;/div&gt; &lt;div class="foo bar"&gt;Some stuff&lt;/div&gt; &lt;div class="foo"&gt;Some stuff&lt;/div&gt; &lt;div class="foo"&gt;Some stuff&lt;/div&gt; &lt;div class="foo"&gt;Some stuff&lt;/div&gt; &lt;div class="foo bar"&gt;Some stuff&lt;/div&gt; &lt;div class="foo"&gt;Some stuff&lt;/div&gt; &lt;div class="foo"&gt;Some stuff&lt;/div&gt; &lt;div class="foo"&gt;Some stuff&lt;/div&gt; &lt;div class="foo bar"&gt;Some stuff&lt;/div&gt; &lt;div class="foo"&gt;Some stuff&lt;/div&gt; &lt;div class="foo"&gt;Some stuff&lt;/div&gt; &lt;div class="foo"&gt;Some stuff&lt;/div&gt; &lt;/div&gt; &lt;!-- #container --&gt; </code></pre> <p>So, obviously <em>all</em> 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 <code>:nth-child(4n+2)</code>, but I can't always count on there being exactly two elements preceding my <code>div</code>s. </p> <p>Is there an nth-child-like selector (or method) that will only take the specified element into consideration when counting?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload