jQuery selector vs hasClass

JavaScript performance comparison

Revision 17 of this test case created by qgustavor

Info

Tests ways that determinate if a element have a class, include the jQuery and HTML5 ones. It also have to return true for "foo" and false to "bar".

Preparation code

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

Preparation code output

Test runner

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

Java applet disabled.

Testing in unknown unknown
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. Here’s a list of current revisions for this page:

1 comment

Gustavo Rodrigues commented :

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

Add a comment