jquery has class before remove and add

Benchmark created by Dan Manastireanu on


Preparation HTML

<span id="elem1" class="a b c d" />
<span id="elem2" class="b" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
  var reset = function() {
   $('#elem1').attr('class', 'a b c d');
   $('#elem2').attr('class', 'b');
  }
  
  var f1 = function(el, cls) {
   reset();
   var $el = $('#' + el);
   if (!$el.hasClass(cls)) {
    $el.removeClass('a b c d').addClass(cls);
   }
  };
  var f2 = function(el, cls) {
   reset();
   $('#' + el).removeClass('a b c d').addClass(cls);
  };
  var f3 = function(el, cls) {
   reset();
   $('#' + el).attr('class', cls);
  };
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
with has test
f1('elem1', 'b');
f1('elem1', 'x');
f1('elem2', 'b');
f1('elem2', 'd');
ready
without has test
f2('elem1', 'b');
f2('elem1', 'x');
f2('elem2', 'b');
f2('elem2', 'd');
ready
attr
f3('elem1', 'b');
f3('elem1', 'x');
f3('elem2', 'b');
f3('elem2', 'd');
ready

Revisions

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

  • Revision 1: published by Dan Manastireanu on
  • Revision 3: published on