<div id="foo"></div>
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
element.className = "bar";
element.className.replace("bar", "");
}
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
element.setAttribute("class", "bar");
element.setAttribute("class", element.getAttribute("class").replace("bar",""));
}
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
element.classList.add("bar");
element.classList.remove("bar");
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
className | |
setAttribute | |
classList |
Test name | Executions per second |
---|---|
className | 5061.4 Ops/sec |
setAttribute | 1036.2 Ops/sec |
classList | 911.1 Ops/sec |
Let's dive into the benchmarking results.
Benchmark Definition
The benchmark tests three different approaches to setting and removing CSS classes on an HTML element:
className
property directly using string manipulation (element.className = "bar";
, followed by element.className.replace("bar", "");
)setAttribute
method with a string value (element.setAttribute("class", "bar");
, followed by element.setAttribute("class", element.getAttribute("class").replace("bar",""));
)classList
API to add and remove classes (element.classList.add("bar");
, followed by element.classList.remove("bar");
)Library/Syntax
There is no external library used in this benchmark.
Test Case Explanations
element.className = "bar";
.element.className.replace("bar", "");
.element.setAttribute("class", "bar");
.element.getAttribute("class")
and replacing "bar" with an empty string.element.classList.add("bar");
.element.classList.remove("bar");
.Pros/Cons
Alternatives
If you need to set or remove multiple classes, consider using the classList approach. If you're working with legacy code or older browsers, the setAttribute method might still be useful.
For setting a single class, the className approach is sufficient and easy to read.
Keep in mind that these results are specific to this particular test case and browser combination (Chrome 120). The performance differences may vary across different browsers and versions.