<div id="foo"></div>
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
element.className += "bar" + i;
}
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
element.setAttribute("class", "bar"+ i);
}
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
element.classList.add("bar" + i);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
className | |
setAttribute | |
classList |
Test name | Executions per second |
---|---|
className | 3.8 Ops/sec |
setAttribute | 2459.5 Ops/sec |
classList | 84.2 Ops/sec |
Overview
The provided benchmark measures the performance of three different approaches for adding a class to an HTML element: className
, setAttribute
, and classList
. The benchmark is designed to compare the execution speed of these methods in modern web browsers.
Benchmark Definition
The benchmark definition json contains the following information:
Name
: "append className vs. setAttribute vs. classList"Description
: nullScript Preparation Code
: nullHtml Preparation Code
: A simple HTML element with an ID "foo".Test Cases
There are three individual test cases, each representing a different approach for adding a class to the HTML element:
className
property to add a class to the element.setAttribute
method to set the class
attribute of the element with the desired value.classList.add()
method to add a class to the element.Options Compared
The benchmark compares the execution speed of three options:
className
property.class
attribute of the element with the desired value using the setAttribute
method.classList.add()
method.Pros and Cons
Here's a brief summary of the pros and cons of each approach:
className
due to attribute lookup.Library
The benchmark uses the classList
property, which is a part of the HTML5 specification. The classList.add()
method is supported by most modern web browsers, but may require additional polyfills for older versions.
Special JS Feature/Syntax
There is no special JavaScript feature or syntax used in this benchmark. However, it's worth noting that the classList
approach relies on the classList
property being implemented correctly by the browser.
Other Alternatives
If you're interested in exploring alternative approaches, here are a few options:
style
attribute.In summary, the className
approach is a simple and widely supported way to add classes to HTML elements, while the setAttribute
method provides an alternative with fast execution. The classList
approach offers more readability and flexibility, but may require additional code and polyfills for older browsers.