<div id="foo"></div>
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
element.className = "bar";
}
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
element.setAttribute("class", "bar");
}
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
element.classList.add("bar");
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
className | |
setAttribute | |
classList |
Test name | Executions per second |
---|---|
className | 61155.7 Ops/sec |
setAttribute | 33624.0 Ops/sec |
classList | 25480.4 Ops/sec |
Let's break down the provided benchmark and explain what's being tested, the options being compared, their pros and cons, and other considerations.
Benchmark Overview
The benchmark measures the performance difference between three ways to set or update the class
attribute of an HTML element: using the className
property, the setAttribute
method, and the classList
API (part of the DOM Standard).
Test Cases
Each test case represents a specific scenario:
class
attribute directly using the element.className = "bar"
syntax.class
attribute using the element.setAttribute("class", "bar")
method.class
attribute using the element.classList.add("bar")
API.Library and Syntax Considerations
The benchmark uses a mix of:
classList
API)The classList
API is a part of the DOM Standard, which provides a way to manage classes in a more modern and efficient manner. It's supported by most modern browsers.
Options Being Compared
The three options being compared are:
class
attribute using the property syntax.class
attribute using the setAttribute
method.className
, allows for setting multiple attributes at once.setAttribute
method.classList
API to manage classes.Other Considerations
When choosing between these options, consider the following:
className
, you may want to stick with it for compatibility reasons. However, if possible, consider refactoring to use more modern and efficient methods like classList
.classList
API is likely to be faster and more efficient than setting the class
attribute directly or using the setAttribute
method.setAttribute
might be a better choice.Alternatives
Other alternatives for managing classes in HTML elements include:
.class-name
) and applying it using the classList.toggle()
method.Keep in mind that these alternatives may have different trade-offs in terms of performance, flexibility, and compatibility.