<div id="foo" class="bar baz"></div>
var test_element = document.getElementById("foo");
var result = test_element.className.indexOf("bar") != -1;
var result = test_element.classList.contains("bar");
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Use hasClass shorthand | |
Use classList |
Test name | Executions per second |
---|---|
Use hasClass shorthand | 10022060.0 Ops/sec |
Use classList | 5034193.0 Ops/sec |
Let's break down what's being tested in this benchmark.
Benchmark Definition
The benchmark is comparing two approaches to check if an element has a specific class: className.indexOf
and classList.contains
. These methods are used to achieve the same goal, but with different syntax and semantics.
Options Compared
The two options being compared are:
className.indexOf
: This method searches for the specified value in the className
property of an element. If found, it returns the index of the occurrence; otherwise, it returns -1.classList.contains
: This method checks if a specific class is present in the classList
property of an element.Pros and Cons
className.indexOf
Pros:
element.className.indexOf('bar') && element.className.indexOf('baz')
)classList
Cons:
classList.contains
because it performs a linear searchclassList.contains
Pros:
className.indexOf
classList
Cons:
Library Used
In this benchmark, the classList
property is being used, which is a part of the DOM Standard (ECMAScript 2015). The classList.contains
method is a built-in method that allows checking for class presence in modern browsers.
Special JS Feature or Syntax
This benchmark uses the ES6 classList
API, which is a newer feature introduced in ECMAScript 2015. This API provides a more efficient and convenient way to work with classes in JavaScript.
Other Alternatives
If you need to support older browsers that don't support classList
, you can use alternative methods such as:
element.className.match(new RegExp('\\bbar\\b'))
)indexOf
method on the class names array (element.className.indexOf('bar') === -1
)However, these alternatives may not be as efficient or convenient as using classList.contains
.
In summary, this benchmark is testing the performance difference between two approaches to check if an element has a specific class: className.indexOf
and classList.contains
. The latter is more efficient and modern, but requires longer syntax.