Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add class from array to n divs using .each function?

Tags:

html

jquery

each

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.

like image 877
user3407278 Avatar asked Aug 08 '26 02:08

user3407278


2 Answers

Modulo [%] is your friend:

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

See fiddle.

like image 80
moonwave99 Avatar answered Aug 10 '26 16:08

moonwave99


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;
  }
});
like image 26
kkemple Avatar answered Aug 10 '26 14:08

kkemple