<div id="foo" class="class1 class2"></div>
var element = document.getElementById("foo");
var i = 1000;
var classListTemp = element.classList;
while (i--) {
classListTemp.add("class3");
}
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
element.setAttribute("class", "class1 class2 class3");
}
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
element.classList.add("class3");
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
classListVar | |
setAttribute | |
classList |
Test name | Executions per second |
---|---|
classListVar | 6764.5 Ops/sec |
setAttribute | 17282.3 Ops/sec |
classList | 6252.0 Ops/sec |
Benchmark Overview
The provided JSON represents a JavaScript microbenchmark on the MeasureThat.net website. The benchmark compares three approaches for adding a class to an existing HTML element: classList
, setAttribute
, and setting a className
attribute directly.
Approaches Compared
classList
property of the DOM element, which allows you to add classes dynamically.setAttribute()
method to set the class
attribute of the element.Pros and Cons of Each Approach
classList
property.classList
in specific scenarios.Library Usage
None of the provided approaches rely on external libraries. However, if you were to use a library like jQuery or Zepto for DOM manipulation, it might provide an additional layer of complexity and performance impact.
Special JS Features/Syntax
The classList
property relies on CSS classes in HTML5, which is a relatively modern feature. Not all browsers support this feature, so you should test your code across different browser versions.
Alternative Approaches
If you're interested in exploring alternative approaches for adding a class to an element, consider the following:
appendChild()
or insertAdjacentHTML()
, could potentially offer better performance.Keep in mind that each approach has its trade-offs, and the best solution will depend on your specific use case, browser requirements, and performance constraints.