<div id="foo" class="test"></div>
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
if(element.className.indexOf("test") > -1) {
element.className = "bar";
}else {
element.className = "test";
}
}
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
if(element.classList.contains("test")) {
element.classList.add("bar");
} else {
element.classList.add("test");
}
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
className | |
classList |
Test name | Executions per second |
---|---|
className | 1482.9 Ops/sec |
classList | 1770.8 Ops/sec |
Let's dive into what is being tested in this benchmark.
The Test Case:
We have two test cases, both aimed at manipulating the class attribute of an HTML element (#foo
). The main difference between these tests lies in how they access and modify the class attribute:
className
test: This test uses the className
property to get and set the value of the class attribute.classList
test: This test uses the classList
API, which provides a more modern way to manage the class list.What's being compared:
We're comparing two approaches:
element.className
(an older method) vs.element.classList
(a newer, more efficient method)Pros and Cons of each approach:
className
approach:classList
, especially when dealing with multiple classes or complex operations.classList
approach:add()
, remove()
, and toggle()
for easier class management.Other considerations:
Alternatives:
For similar class manipulation tasks:
class
attribute and CSS selectors for styling and behavior control.This benchmark highlights the performance differences between two approaches to managing HTML element classes. While both methods work, the newer classList
API offers improved efficiency and is a better choice for large-scale applications or browsers that support it.