<div id="foo"></div>
function addClass(el, classNames)
{
if (!classNames) { return; }
if (!Object.prototype.toString.call(classNames) === "[object Array]")
{
classNames = classNames.split(' ');
}
var className = el.getAttribute("class") || "";
var i, classMap = {}, currentClasses = [], length;
if (className !== null)
{
currentClasses = className.split(" ");
length = currentClasses.length;
for (i = 0; i < length; i++)
{
if (currentClasses[i] !== "")
{
classMap[currentClasses[i]] = "";
}
}
}
var changed = false, trimmedName;
var newAdded = [];
length = classNames.length;
for (i = 0; i < length; i++)
{
trimmedName = classNames[i].trim();
if ((trimmedName.length > 0) && !(trimmedName in classMap))
{
currentClasses.push(trimmedName);
newAdded.push(trimmedName);
classMap[trimmedName] = "";
changed = true;
}
}
if (changed)
{
el.setAttribute("class", currentClasses.join(" ").trim());
}
return newAdded;
}
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
addClass(element, "bar");
}
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
element.classList.add("bar");
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
addClass function | |
classList |
Test name | Executions per second |
---|---|
addClass function | 426.4 Ops/sec |
classList | 2794.9 Ops/sec |
Benchmark Analysis
The provided benchmark measures the performance of two approaches to add classes to an HTML element: using a custom addClass
function and using the classList.add()
method.
Custom addClass
Function
The custom addClass
function is used in the first test case. This approach is implemented as a self-contained JavaScript function that takes an element and an array of class names as arguments. The function iterates through the class names, checks if each name is not empty, and adds it to the element's class
attribute if it's not already present.
Pros:
Cons:
classList.add() Method
The classList.add()
method is used in the second test case. This approach is part of the Web APIs, specifically the DOM API, and provides a simple way to add classes to an element.
Pros:
classList.add()
method is implemented as a direct call to the browser's internal logic, minimizing overhead.Cons:
Other Considerations
classList.add()
method is more widely supported due to its standardization in Web APIs.addClass
function by using techniques like caching or memoization to reduce runtime overhead.Alternative Approaches
class
attribute using string concatenation or other techniques.In summary, the choice between the custom addClass
function and the classList.add()
method depends on the specific requirements and constraints of the project. The classList.add()
method is generally a more efficient and convenient option, but the custom function provides flexibility and control.