Adding Classes JQuery and Javascript

JavaScript performance comparison

Revision 3 of this test case created by Jeff Monschke

Preparation code

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

      
<script>
Benchmark.prototype.setup = function() {
  (function($) {
      $.fn.addClassPM = function(cls){
          if(typeof cls !== 'undefined'){
              var length = this.length,
              i = 0,
              tokens = cls.split(" "),
              tokenLength = tokens.length,
              j = 0;
              for(;i<length;i+=1){
                  if(this[i].classList){
                      for(;j<tokenLength;j+=1){
                          this[i].classList.add(tokens[j]);
                      }
                  }
                  else{
                      this[i].className+=' '+cls;
                  }
              }
          }
          return this;
      };
  })(jQuery);

};
</script>

Preparation code output

<div class="jeff"></div> <div class="jeff"></div> <div class="jeff"></div> <div class="jeff"></div> <div class="jeff"></div> <div class="jeff"></div> <div class="jeff"></div> <div class="jeff"></div> <div class="jeff"></div> <div class="jeff"></div> <div class="jeff"></div>

Test runner

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

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
jQuery
jQuery(".jeff").addClass("jeff1");
pending…
JavaScript
jQuery(".jeff").addClassPM("jeff1");
pending…
JavaScript 2 Classes
jQuery(".jeff").addClassPM("jeff1 jeff2");
pending…
jQuery 2 Classes
jQuery(".jeff").addClass("jeff1 jeff2");
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.

0 Comments