Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Target every nth iteration of an element that has specific class

Tags:

jquery

css

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");
});
like image 660
John the Painter Avatar asked Mar 16 '17 14:03

John the Painter


1 Answers

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>
like image 123
Nenad Vracar Avatar answered Oct 13 '22 08:10

Nenad Vracar