I know I cannot do this with CSS but I'm wondering, with jQuery, if it's possible to target every nth iteration of an element that has a specific class. So if I wanted to select every fourth .media
element or every third .media
item.
For example:
<ul>
<li class="element"></li>
<li class="element"></li>
<li class="element media"></li>
<li class="element media"></li>
<li class="element"></li>
<li class="element media"></li>
<li class="element"></li>
<li class="element media"></li>
</ul>
$('.layout-option--b .media').each(function() {
$(this).filter(function(index, element) {
return index % 4;
}).addClass("fourth");
});
Yes you can use filter()
for this and check elements index using %
. Because i
starts from 0 you can use i + 1
.
$('li.media').filter(function(i) {
return (i + 1) % 4 == 0
}).css('color', 'red')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="element">Li</li>
<li class="element">Li</li>
<li class="element media">Li</li>
<li class="element media">Li</li>
<li class="element">Li</li>
<li class="element media">Li</li>
<li class="element">Li</li>
<li class="element media">Li</li>
</ul>
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