Applying one of an array of styles to each selected item

JavaScript performance comparison

Test case created by FW

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<div class="tripItem">
</div>
<div class="tripItem">
</div>
<div class="tripItem">
</div>
<div class="tripItem">
</div>

Preparation code output

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Felix Kling
var classes = ['blue', 'red', 'green'],
    len = classes.length;

$('div.tripItem').addClass(function(i) {
  return classes[i % len];
});
pending…
wanovak
var num = 0;
var colors = ['blue', 'red', 'green'];
$('.tripItem').each(function() {
  if (num >= colors.length) return false;
  $(this).addClass(colors[num]);
  num++;
});
pending…
Raminson
var i = 0;
var cls = ['blue','red','green']
$('.tripItem').each(function(){
  $(this).addClass(cls[i]);
  i++;
  if (i == 3) {i = 0}    
})
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment