You can loop over the colors also just by using the modulo operator instead:
$('a').each(function(i){ i = ++i % 4; var color = i == 1 ? 'red' : //first 4 i == 2 ? 'blue' : //second group of 4 i == 3 ? 'yellow' : // third group 'lime'; //fourth group and so on $(this).css('backgroundColor', color); }); On 23 jan, 15:38, devilmike <devilm...@gmail.com> wrote: > Awesome Ricardo, thanks! I guess the only issue I have is that I'll > never know how many "sets of4" I'll be dealing with, and i apologize > for not explaining myself very well in my example. Basically for each > "set", I want to run the same function. This is what I came up with. > It works, but I'm a bit concerned about the amount of looping going > on. Your code seems much cleaner... > > var result = $('a'); > var theCount =4; //variable passed in > var oldCount = -1; > var theRow = result; > > while (theRow.length > 1){ > theRow = jQuery.grep(result, function(n, i){ > return (n && i < theCount && i > oldCount ); > }); > oldCount = theCount - 1; > theCount = theCount +4; > > $(theRow).each(function(i, o){ > // do something to each item of each set}); > > }