jQuery CSS vs addClass speed (v17)

Revision 17 of this benchmark created by Don on


Description

A modified version of the first few revisions that accounts for any speedup gained when referencing the same jQuery object in a variable instead of repeatedly using the jQuery selector.

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>

Setup

var jqueryDiv = $('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
Add Class
$('div').addClass('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
Remove and Add class (jQuery Object Predefined)
jqueryDiv.removeClass('otherClass').addClass('newClass');
ready
Apply CSS (jQuery Object Predefined)
jqueryDiv.css({'background-color':'red'});
ready
Add Class (jQuery Object Predefined)
jqueryDiv.addClass('newClass');
ready

Revisions

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