jQuery hasClass vs. addClass and removeClass (v5)

Revision 5 of this benchmark created by Dave Clark on


Description

Test the performance of toggling classes in jQuery vs. checking if a class exists before (possibly unnecessary) manipulation. This test both removes and adds the class in order to create a cyclically reusable test case.

Preparation HTML

<div class="test blue"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

Test runner

Ready to run.

Testing in
TestOps/sec
hasClass + remove/addClass
var $test = $('.test');
if ($test.hasClass('blue')) { $test.removeClass('blue'); }
if (!$test.hasClass('blue')) { $test.addClass('blue'); }
ready
remove/addClass
var $test = $('.test');
$test.removeClass('blue');
$test.addClass('blue');
ready
hasClass only
var $test = $('.test');
$test.hasClass('blue');
$test.hasClass('blue');
ready

Revisions

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