setAttribute('class') vs classList.add

JavaScript performance comparison

Test case created by Jamie

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var myDiv = document.createElement('div');
};

Benchmark.prototype.teardown = function() {
    myDiv.setAttribute('class', ''); // Reset
};
</script>

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
setAttribute
// Add two classes
myDiv.setAttribute('class', 'myClass myOtherClass');
// Remove one
var classes = myDiv.getAttribute('class');
classes = classes.replace('myClass ','');
myDiv.setAttribute('class', classes);
pending…
classList.add
// Add two classes
myDiv.classList.add('myClass');
myDiv.classList.add('myOtherClass');
// Remove one
myDiv.classList.remove('myClass');
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