Modulo [%
] is your friend:
var colours = ['red', 'green', 'blue'];
$('.box').each(function(index, element) {
$(element).addClass(colours[index % colours.length]);
});
Question
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.
Solution
Modulo [%
] is your friend:
var colours = ['red', 'green', 'blue'];
$('.box').each(function(index, element) {
$(element).addClass(colours[index % colours.length]);
});
OTHER TIPS
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;
}
});
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;
}
var arr = ['red', 'green', 'blue'];
$('.box').each(function(i,o) {
$(this).addClass(arr[i%arr.length]);
});