3

Basically what I'm trying to do is this

var arr = ["red","green","blue"];
$('.box').each(function() {
    $(this).addClass(Array Value Here)
});

and I want the result to be like this.

<div class"box red"></div>
<div class"box green"></div>
<div class"box blue"></div>
<div class"box red"></div>
<div class"box green"></div>
<div class"box blue"></div>
<div class"box red"></div>
<div class"box green"></div>
<div class"box blue"></div>

How can I do that? The number of total divs are unknown.

1
  • You are highly encouraged to accept someone's answer. Commented Mar 11, 2014 at 20:32

4 Answers 4

9

Modulo [%] is your friend:

var colours = ['red', 'green', 'blue'];
$('.box').each(function(index, element) {
  $(element).addClass(colours[index % colours.length]);
});

See fiddle.

Sign up to request clarification or add additional context in comments.

4 Comments

It does work. I was in the process of writing this same answer: jsbin.com/nojipowo/2/edit?html,css,js,output
it works Thanks!! From where can I learn about this % ? if you don't mind...Could you explain how this works?
It returns the remainder of two numbers.
@user3407278 wiki is your friend.
2
var arr = ['red', 'green', 'blue'],
i = 0,
len = arr.length;

$('.box').each(function(index, box) {
  console.log(box);
  $(box).addClass(arr[i]);
  ++i;
  if (i === len) {
    i = 0;
  }
});

1 Comment

Could you make a jsfiddle?
0

If you're just styling you can avoid the JS all together by using :nth-child.

.box:nth-child(3n + 1) {
  color: red;
}

.box:nth-child(3n + 2) {
  color: green;
}

.box:nth-child(3n + 3) {
  color: blue;
}

Comments

0
     var arr = ['red', 'green', 'blue'];
      $('.box').each(function(i,o) {
         $(this).addClass(arr[i%arr.length]);
     });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.