jQuery selector vs hasClass (v30)

Revision 30 of this benchmark created on


Description

Test which is faster, a selector including the class compared to hasClass.

Preparation HTML

<script src="//code.jquery.com/jquery-git2.min.js"></script>

<div class="foo"></div>

<script>
  var found = false;
  $("body").addClass("foobar");
</script>

Setup

var cachedBody = document.body,
        cachedIndexOf = Array.prototype.indexOf;

Test runner

Ready to run.

Testing in
TestOps/sec
selector
if ($("body.foobar").length) {
 found = true;
}
ready
hasClass
if ($("body").hasClass("foobar")) {
 found = true;
}
ready
native
if (document.body.className.indexOf('foobar') > -1) {
 found = true;
}
ready
Native cached body
if (cachedBody.className.indexOf('foobar') > -1) { 
 found = true;
}
ready
Native cached body + indexOf
if (cachedIndexOf.call(cachedBody.className, 'foobar') > -1) { 
 found = true;
}
ready
native classList.contains
if (document.body.classList.contains("foobar")) {
 found = true;
}
ready
cached classList.contains
if (cachedBody.classList.contains("foobar")) {
 found = true;
}
ready

Revisions

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