jQuery CSS vs addClass speed (v3)

Revision 3 of this benchmark created on


Preparation HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>

<style type="text/css">
.newClass {
background-color:red;
}

.otherClass {
background-color: green;
}
</style>

<div id="c1"><div class="otherClass">Hi</div></div>

Teardown


    $('#c1').replaceWith('<div id="c1"><div class="otherClass">Hi</div></div>');
    
  

Test runner

Ready to run.

Testing in
TestOps/sec
Remove and Add class
$('.otherClass').removeClass('otherClass').addClass('newClass');
ready
Apply CSS
$('.otherClass').css({'background-color':'red'});
ready
Add Class
$('.otherClass').addClass('newClass');
ready
Plain JS Replace Class
var elem = document.getElementById('c1').childNodes[0];
elem.setAttribute('class', elem.getAttribute('class').replace('otherClass', 'newClass')); 
ready
Plain JS Replace Class v2
var elem = document.getElementById('c1').childNodes[0];
elem.className = elem.className.replace('otherClass', 'newClass');
ready
classList api add+rem
var elem = document.getElementById('c1').childNodes[0];
elem.classList.remove('otherClass');
elem.classList.add('newClass');
ready

Revisions

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