I have a structure like this:
<div class="parent">
<div class="randomclass">...</div>
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
<div class="randomclassdifferentname">...</div>
<div class="item">Item 4</div>
<div class="item">Item 5</div>
<div class="item">Item 6</div>
<div class="item">Item 7</div>
...
</div>
<div class="parent">
<div class="anotherclass">...</div>
<div class="item">Another item 1</div>
<div class="item">Another item 2</div>
<div>...</div>
<div class="item">Another item 3</div>
...
</div>
I need to select only nth .item div class child of a .parent div (counter resets for every parent node).
For example I want to select every third "div.item" element so I'm expecting to affect elements with content "Item 3", "Item 6", "Another item 3".
Rules:
Unfortunatelly CSS selector:
div.parent div.item:nth-child(3n)
with nth-child() is not working properly. Although the effects are applied only to elements with given class, the counting itself is not correct because it counts also elements without given class.
As I doubt that there will be pure CSS solution and also because I'm in fact using this as a jQuery selector, I would like some simple jQuery alternative. Thank you guys for any help you can give me.
You can filter the items based on the index they have in the parent, in relation to other items with the same class
$('.item').filter(function(_,item) {
return ($(item).siblings('.item').addBack().index(item)+1) % 3 === 0;
}).css('color','red');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
<div class="randomclass">...</div>
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
<div class="randomclassdifferentname">...</div>
<div class="item">Item 4</div>
<div class="item">Item 5</div>
<div class="item">Item 6</div>
<div class="item">Item 7</div>
...
</div>
<div class="parent">
<div class="anotherclass">...</div>
<div class="item">Another item 1</div>
<div class="item">Another item 2</div>
<div>...</div>
<div class="item">Another item 3</div>
...
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With