Add Class Name

JavaScript performance comparison

Test case created by The Able Few

Info

className vs setAttribute

Preparation code

<div id="this-thing" class="">Things</div>
<script>
Benchmark.prototype.setup = function() {
    var el = document.getElementById('this-thing');
   
    var removeClass = function(obj, str) {
      var reg = new RegExp(" *" + str, "g");
      obj.setAttribute("class", obj.getAttribute("class").replace(reg, ''));
    };
   
    var addClassName = function(obj, str) {
      obj.className = obj.className + ' ' + str;
      //removeClass(obj, str);
    };
    var addClassAttr = function(obj, str) {
      obj.setAttribute("class", obj.getAttribute("class") + ' ' + str);
      //removeClass(obj, str);
    };
   
};
</script>

Preparation code output

Things

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
className
addClassName(el, 'new-class-name');
pending…
setAttribute
addClassAttr(el, 'new-class-name');
pending…

You can edit these tests or add even more tests to this page by appending /edit to the URL.

Compare results of other browsers

0 comments

Add a comment