hasClass()

JavaScript performance comparison

Test case created by Nathan

Preparation code

<button class="btn btn-success" id="success"></button>
<button class="btn btn-danger" id="danger"></button>

<script>
var searchClass = "btn-success",
    elWith = document.getElementById('success'),
    elWithout = document.getElementById('danger');

HTMLElement.prototype.hasClass = function(className) {
    return new RegExp('(?:^|\\s)' + className + '(?:\\s|$)').test(this.className);
}

HTMLElement.prototype.hasClassNative = function(className) {
    return this.classList.contains(className);
}
</script>

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
HasClass w/ RegExp
elWith.hasClass(searchClass);
elWithout.hasClass(searchClass);
pending…
Native classList.contains()
elWith.hasClassNative(searchClass);
elWithout.hasClassNative(searchClass);
pending…

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

Compare results of other browsers

0 comments

Add a comment