Pure js hasClass vs jQuery hasclass (v40)

Revision 40 of this benchmark created on


Preparation HTML

<div class="super cali frag ilist ic expi ali docious tinker tailor soldier sailor richman poorman beggarman Thief" id="someElement"></div><script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
  var el = document.getElementById('someElement');
  
function hasClassIteration(el, selector) 
{
   for(var i = 0, j = 0, cls = el.className, c = cls.length, s = selector.length, code; i < c; i++)
   {
      code = cls.charCodeAt(i);
      if (code == selector.charCodeAt(j))
      {
        j++;
      }
      else
      {
          if (j == s && code == 32)
          {
             return true;
          }
          else
          {
            j = 0;
          }
      }
   }
   return (j == s) ? true : false; 
}
  
function hasClass(el, selector) {
    return (" " + el.className + " ").indexOf(" " + selector + " ") > -1
  }

  function hasClassRegex(el, selector) {
    return (el.className && new RegExp("(^|\\s)" + selector + "(\\s|$)").test(el.className));
  }

  function classListContains(el, selector){
    return el.classList.contains(selector);
  }
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
jQuery
$(el).hasClass('Thief');
ready
Pure JS - indexOf
hasClass(el, 'Thief');
ready
With classic Iteration
hasClassIteration(el, 'Thief');
ready
DOM
classListContains(el, 'Thief');
ready

Revisions

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