<div id="foo"></div>
var element = document.getElementById("foo");
var i = 10000;
while (i--) {
const isFooClass = element.className.includes("foo");
}
var element = document.getElementById("foo");
var i = 10000;
while (i--) {
var isFooClass = element.getAttribute("class") === "foo";
}
var element = document.getElementById("foo");
var i = 10000;
while (i--) {
var isFooClass = element.classList.contains("foo");
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
className | |
getAttribute | |
classList |
Test name | Executions per second |
---|---|
className | 24494.3 Ops/sec |
getAttribute | 11370.2 Ops/sec |
classList | 4908.6 Ops/sec |
The provided benchmark measures the performance of three different approaches to check if an HTML element has a specific class:
className
: This approach uses the includes()
method to search for the class name in the className
property of the element.getAttribute
: This approach uses the getAttribute()
method to retrieve the value of the class
attribute and then checks if it equals the class name.classList
: This approach uses the contains()
method of the classList
property to check if the class name is present in the list of classes.Here are some pros and cons of each approach:
className
Pros:
Cons:
includes()
method's time complexity).foo-
)getAttribute
Pros:
Cons:
.foo-
)classList
Pros:
classList
propertyCons:
The choice of approach depends on the specific requirements and constraints of the project. If performance is critical and compatibility with older browsers is not a concern, getAttribute
might be the best option. However, for most modern web applications, classList
is likely to be the fastest and most efficient way to check for class presence.
In this benchmark, classList
appears to be the slowest approach, but it's still faster than className
due to its direct access to the list of classes. The difference in performance between getAttribute
and classList
is relatively small, likely due to Chrome 77's optimization for this specific use case.
Other alternatives to consider:
.foo
) instead of checking class presence directlyhasClass()
method)