Pure js hasClass vs jQuery hasclass (v17)

Revision 17 of this benchmark created on


Description

Additional comparison of className

Preparation HTML

<div class="someClass" id="someElement">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<script>
  var el = document.getElementById('someElement');

  function hasClass(el, selector) {
    var className = " " + selector + " ";

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


    return false;
  }

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

    return false;
  }

  function hasClass3(el, cls) {
    return (new RegExp("(^|\\s)" + cls + "(\\s|$)")).test(el.className);
  }
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
jQuery
// async test
$(el).hasClass('someClass');
ready
Pure JS (className)
// async test
hasClass(el, 'someClass');
ready
Pure JS (getAttribute)
// async test
hasClass2(el, 'someClass');
ready
RegExp
// async test
function hasClass3(el, 'someClass');
ready

Revisions

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