jQuery CSS vs addClass speed (v7)

Revision 7 of this benchmark created by DasRed 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 class="some preexisting classes"></div>

Teardown


    $('div').remove();
    $('body').append('<div class="some preexisting classes otherClass"></div>');
    
  

Test runner

Ready to run.

Testing in
TestOps/sec
Remove and Add class
$('div').removeClass('otherClass').addClass('newClass');
ready
Apply CSS
$('div').css({'background-color':'red'});
ready
Edited
var elem = $('div')[0];
elem.setAttribute('class', elem.getAttribute('class').replace('otherClass', 'newClass')); 
 
ready
Plain JS Replace Class
var elem = document.getElementsByTagName('div')[0];
elem.setAttribute('class', elem.getAttribute('class').replace('otherClass', 'newClass')); 
 
ready
Plain JS Replace Class v2
var elem = document.getElementsByTagName('div')[0];
elem.className = elem.className.replace('otherClass', 'newClass');
ready
Plain JS ClassList
var elem = document.querySelector('div');
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.