jQuery selector vs hasClass

JavaScript performance comparison

Revision 17 of this test case created by qgustavor

Preparation code

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
</head>
<body class="foo">
<div class="bar"></div>
</body>
</html>
    

Preparation code output

<html> <head> </head> <body class="foo"> <div class="bar"></div> </body> </html>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
native javascript
document.body.className.indexOf("foo") !== -1;
document.body.className.indexOf("bar") !== -1;
pending…
native selector and .hasClass()
$(document.body).hasClass("foo");
$(document.body).hasClass("bar");
pending…
$ and .hasClass()
$("body").hasClass("foo");
$("body").hasClass("bar");
pending…
$ and .is()
$("body").is(".foo");
$("body").is(".bar");
pending…
$ and length
$("body.foo").length !== 0;
$("body.bar").length !== 0;
pending…
Element.classList
document.body.classList.contains('foo');
document.body.classList.contains('bar');
pending…
document.querySelector
document.querySelector('body.foo')!==null;
document.querySelector('body.bar')!==null;
pending…

Compare results of other browsers

Revisions

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

1 Comment

Gustavo Rodrigues commented :

Why Element.classList is faster than using .className.indexOf in most browsers except Chrome?