<div id="foo" class="test"></div>
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
(( ' ' + element.className + ' ').indexOf("test") > -1)
}
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
element.classList.contains("test");
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
className | |
classList |
Test name | Executions per second |
---|---|
className | 2980.0 Ops/sec |
classList | 269400.5 Ops/sec |
Let's break down the benchmark and explain what is being tested.
Benchmark Overview
The benchmark compares two approaches to check if an HTML element has a specific class: indexOf
vs. classList.contains
. The test case uses a simple HTML structure with a single div element, and a JavaScript script that runs a loop 1000 times, repeatedly checking the presence of a specific class.
Options Compared
The benchmark compares two options:
className.indexOf("test") > -1
: This approach uses the indexOf
method to search for the string "test" within the value of the className
property of an HTML element. If the string is found, the method returns a non-negative index; otherwise, it returns -1.element.classList.contains("test")
: This approach uses the classList.contains()
method to check if the "test" class is present in the list of classes associated with an HTML element.Pros and Cons
indexOf
approach:null
, undefined
) in the className
property, which can lead to unexpected results.classList.contains()
approach:Library Used
In this benchmark, the classList
property is used in conjunction with the contains()
method. The classList
property is a standard HTML5 feature that allows you to interact with an element's class list. It provides several methods for working with classes, including contains()
, which checks if a specific value is present in the class list.
Special JS Feature or Syntax
None of the test cases use any special JavaScript features or syntax beyond the standard language.
Other Considerations
When running this benchmark, it's essential to consider the following:
className
property may contain other classes besides "test", which can influence the results.indexOf()
can lead to slower performance when dealing with large class lists or when the element has no classes.Alternative Approaches
Some alternative approaches to check if an HTML element has a specific class include:
querySelector
method, which is generally faster than indexOf
. However, it requires that you use a CSS selector.hasClass()
method for checking classes.Keep in mind that these alternatives may have different performance characteristics and might not be as straightforward to implement as the classList.contains()
approach.