<div id="foo"></div>
var element = document.getElementById("foo");
element.className = "bar";
element.setAttribute("class", "bar");
element.classList.add("bar");
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
className | |
setAttribute | |
classList |
Test name | Executions per second |
---|---|
className | 30689522.0 Ops/sec |
setAttribute | 20164368.0 Ops/sec |
classList | 11047439.0 Ops/sec |
Let's break down the provided benchmark and explain what is being tested, along with the pros and cons of each approach.
What is being tested?
The benchmark compares three ways to set a CSS class on an HTML element:
className
setAttribute
(with "class" as the attribute name)classList
(using the classList
property)Each test case uses a different syntax to set the CSS class, and the benchmark measures their performance in terms of executions per second.
Options compared:
className
: This method sets the value of the className
attribute directly on the element.setAttribute
: This method uses the setAttribute
method to set a custom attribute on the element with the value "class" and then sets the value of the class using string concatenation or interpolation.classList
: This method uses the classList
property to add a new class or modify an existing one.Library used:
The benchmark does not explicitly mention any libraries. However, the use of classList
suggests that the benchmark is assuming a modern browser that supports this property.
Special JS feature or syntax:
There are no special JavaScript features or syntaxes mentioned in the benchmark.
Other alternatives:
In addition to the three methods being tested (className
, setAttribute
, and classList
), other approaches to set a CSS class on an element might include:
style
attribute directly (e.g., using element.style.cssClass = 'bar';
)These alternatives may have different performance characteristics and trade-offs, depending on the specific use case and requirements.