<div id="foo" class="bar baz"></div>
var test_element = document.getElementById("foo");
function hasClass(element, classes) {
classes = classes.split(' ');
for (var i = 0; i < classes.length; i++) {
if (!element.classList.contains(classes[i])) {
return false;
}
}
return true;
};
hasClass(test_element, "bar baz");
test_element.classList.contains("bar");
test_element.classList.contains("baz");
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Use hasClass shorthand | |
Use classList |
Test name | Executions per second |
---|---|
Use hasClass shorthand | 7729117.5 Ops/sec |
Use classList | 7416455.5 Ops/sec |
I'd be happy to help explain the provided benchmark.
What is being tested?
The benchmark is testing two approaches for checking if an element has a specific class:
hasClass
shorthand: This function checks if an element has one or more classes by splitting the class name into individual classes and using the classList.contains()
method to check each class.classList.contains()
: This method directly checks if an element has a specific class.Options compared
The two options being compared are:
hasClass
shorthand: This approach uses a custom function to manually split the class name and use the classList.contains()
method for each individual class.classList.contains()
: This approach directly uses the classList.contains()
method to check if an element has a specific class.Pros and Cons of each approach
hasClass
shorthand:classList.contains()
: Library
The benchmark uses the document
object from the DOM (Document Object Model) library, which provides a way to interact with HTML documents in JavaScript. Specifically, it's using:
document.getElementById()
: To retrieve an element by its ID.classList.contains()
: A built-in method on the Element
interface that checks if an element has a specific class.Special JS feature/syntax
There is no special JavaScript feature or syntax being tested in this benchmark. The code is straightforward and relies solely on the classList
property of HTML elements, which was introduced in ECMAScript 5 (ES5) as part of the standard for modern web browsers.
Other alternatives
For this specific task, using a built-in method like classList.contains()
is often considered the best approach. However, if you need more flexibility or control over the class checking process, the custom implementation of the hasClass
shorthand might be a viable alternative.
Some other alternatives to the hasClass
shorthand could include:
.hasClass()
method.Array.prototype.some()
and element.classList.contains()
.classList
.However, these alternatives may add unnecessary complexity or dependencies to the codebase.