Pure js hasClass vs jQuery hasclass (v16)

Revision 16 of this benchmark created on


Description

Additional comparison of className and getAttribute("class")

Preparation HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<div class=" this is just a test case mother someClass " id="someElement"></div>
<script>
  var el = document.getElementById('someElement');
  
  function hasClass(el, selector) {   
   return (' ' + el.className + ' ').indexOf(" " + selector + " ") > -1
  }
  


  function hasClass2(el, selector) {
  
   if (("" + el.className + "").replace(/[\n\t]/g, " ").indexOf(" " + selector + " ") > -1) {
    return true;
   }
   return false;
  }

function hasClass3(el, selector) {
   if (el.className.match("\b"+selector+"\b")){return true;}return false;}

function hasClass4(el, selector) {
   var pattern = new RegExp('/(.*)(' + selector + ')(.*)', 'gi');
      return el.className.replace(pattern , '$2') == selector;
}

 function hasClass5(el, selector) {
  
   return (("" + el.className + "").replace(/[\n\t]/g, " ").indexOf(" " + selector + " ") > -1)

}

function hasClass6(el, selector) {
    return el.className.replace(new RegExp('(.*)(' + selector + ')(.*)', 'gi') , '$2') == selector;
}

function hasClass7(el, selector) {
    return el.className.replace(new RegExp('(.*)(' + selector + ')(.*)', 'g') , '$2') == selector;
}

</script>

Test runner

Ready to run.

Testing in
TestOps/sec
hasClass3
hasClass3(el, 'someClass'); 
ready
Pure JS (className)
hasClass(el, 'someClass');
ready
Pure JS (getAttribute)
hasClass2(el, 'someClass');
ready
PureJS replace
hasClass4(el, 'someClass');
ready
Quick return hasClass2
hasClass5(el, 'someClass');
ready
less variables replace
hasClass6(el, 'someClass')
ready
jquery
$(el).hasClass('someClass')
ready
replace case sensitive
hasClass7(el, 'someClass')
ready

Revisions

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