NooBskie NooBskie - 2 months ago 11
jQuery Question

alternating between three different classes in an each loop

My current code is setup like this:

var accounts = ['gobaopals', 'baopals05', 'baopals02'];
$('.orderId').each(function() {
var index = $(this).index();
if (index < accounts.length) {
$(this).closest('tr').parent().parent().parent().addClass(accounts[index]);
}
});


What Im trying to do is alternate between classes for each table row I have but everything seems to be getting the
gobaopals
class? What is the proper way to
addClass
and cycle through my three classes?

Answer

From what I see in the code, the .index() method returns the current childs position relative to the parent.

It would seem that if the method is constantly adding the gaobapals class, the DOM structure is similar to

<div>
  <div class="orderId"></div>
</div>

A simple way to implement this is to use a fancy closure

var accounts = ['gobaopals', 'baopals05', 'baopals02'];
var index = 0;
$('.orderId').each(function() {

    if (index < accounts.length) {
      $(this).closest('tr').parent().parent().parent().addClass(accounts[index]);
      index += 1;
      index = index % 3;      
    }
});            
Comments