<div id="foo" class="demo"></div>
var element = document.getElementById("foo");
var i = 1000;
while(i > 0) {
element.className += " bar bar2 bar3";
i--;
element.className = "demo"
}
var element = document.getElementById("foo");
var i = 1000;
while(i > 0) {
element.setAttribute("class", "demo bar bar2 bar3");
i--;
element.className = "demo"
}
var element = document.getElementById("foo");
var i = 1000;
while(i > 0) {
element.classList.add("bar");
element.classList.add("bar2");
element.classList.add("bar3");
i--;
element.className = "demo"
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
className | |
setAttribute | |
classList |
Test name | Executions per second |
---|---|
className | 1608.1 Ops/sec |
setAttribute | 1808.0 Ops/sec |
classList | 679.0 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Overview
The benchmark compares three ways to update the class list of an HTML element:
className
propertysetAttribute
method with a string valueclassList
API (introduced in ECMAScript 5)Options Compared
className
property: This is a property that allows setting and getting the CSS class name of an element.setAttribute
method: This is a method that sets the value of a specific attribute on an element. In this case, it's used to set the class
attribute with a string value.classList
API: This is a modern API that allows adding, removing, and manipulating CSS class names of an element.Pros and Cons
className
property:setAttribute
method:classList
.className
property or classList
.classList
API:Library and Purpose
None of these options require a library; they are built-in JavaScript features or APIs.
Special JS Feature/Syntax
The classList
API is a relatively modern feature that allows manipulating CSS class names. It was introduced in ECMAScript 5 (2009) as part of the HTML5 specification. This means that older browsers, like Internet Explorer 8 and earlier, might not support it.
Other Alternatives
If you need to update the class list of an element on older browsers or require more control over the attribute's value type, you could consider using other approaches:
setAttribute
with a different strategy (e.g., setting the attribute's value as a string, then parsing and splitting it).class
attribute) if you don't need to dynamically manipulate the class list.Keep in mind that each approach has its trade-offs, and the choice ultimately depends on your specific use case, browser support requirements, and performance considerations.