Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Give every first, second and third element a unique class using jQuery

I'm using a jQuery selector to return objects.

For example var target = $('.target'); will return 6 objects.

The objects do not have the same parent.

I want to give each object classes like so:

target[0].addClass('top');
target[1].addClass('middle');
target[2].addClass('low');
target[3].addClass('top');
target[4].addClass('middle');
target[5].addClass('low');

And so on... I thought I could use some modulus. I know the following is wrong.

target.each(function(index){
    index += 1;

    if (index % 3 === 0) {
      $(this).addClass('low');
    } else if(index % 2 === 0) {
      $(this).addClass('middle');
    } else {
      $(this).addClass('top');
    }
}

Is there an easy way that i'm over looking?

like image 661
Steven_Harris_ Avatar asked Sep 16 '15 00:09

Steven_Harris_


1 Answers

This should do what you want

var classes = ['top', 'middle', 'low'];

target.each(function(index){
    $(this).addClass( classes[index % 3] );
}

Working demo

var classes = ['top', 'middle', 'low'];

$(function() {
  var target = $('.target');
  target.each(function(index) {
    $(this).addClass(classes[index % 3]);
  });
});
.top {
  color: red;
}
.middle {
  color: green;
}
.low {
  color: cyan;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="target">1</div>
<div class="target">2</div>
<div class="target">3</div>
<div class="target">4</div>
<div class="target">5</div>
<div class="target">6</div>
like image 167
Gabriele Petrioli Avatar answered Sep 24 '22 03:09

Gabriele Petrioli