0

I want to append different classes to a set of repeating elements.

<div class="widget"></div>
<div class="widget"></div>
<div class="widget"></div>
<div class="widget"></div>

I want to style the above div elements by appending different style classes to them.

It should become like this

<div class="widget fg-white"></div>
<div class="widget fg-black"></div>
<div class="widget fg-red"></div>
<div class="widget fg-green"></div>

I know the direct CSS editing technique using jquery that is described here . But here, I want to append classes which already have the styles that I want.

Community
  • 1
  • 1
Nigel
  • 387
  • 4
  • 13

2 Answers2

3

You can use:

var colors = ["white", "black", "red", "green"];

$('.widget').each(function(i) {
  $(this).addClass("fg-"+colors[i % colors.length]);
});

Working Demo

Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
1

You may use like this:

var klasses = ['fg-white','fg-black','fg-red','fg-green'];
$('.widget').each(function(){
   return $(this).addClass(function(i){
      return klasses[i];
   });
});
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231