<div id="testDiv" class="test1 test2">Sample div</div>
var div = document.getElementById('testDiv');
div.className.includes("test1");
div.className.includes("test2");
var div = document.getElementById('testDiv');
div.classList.contains("test1");
div.classList.contains("test2");
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
className | |
classList |
Test name | Executions per second |
---|---|
className | 1133950.6 Ops/sec |
classList | 908613.6 Ops/sec |
Measuring the performance of different approaches to check if an HTML element has a certain class can be useful in various web development scenarios.
Benchmark Overview
The provided benchmark compares two approaches:
className.includes()
: This method checks if the className
property of an HTML element contains a specific string.classList.contains()
: This method checks if the classList
property of an HTML element contains a specific string.Pros and Cons of Each Approach
classList
.classList.contains()
due to the use of the includes()
method, which scans through the string for a match.className.includes()
, as it only checks for exact matches in the classList
array.classList
property.Library Used
The benchmark uses the Web APIs, specifically:
document.getElementById()
: Retrieves an HTML element by its ID.element.classList
: Accesses the classList
property of an HTML element.Note that classList
is a part of the W3C web standards, and most modern browsers support it. However, older browsers may not have this feature or might require additional code to implement it.
Special JS Features/Syntax
This benchmark does not use any special JavaScript features or syntax beyond what's required for basic Web API functionality.
Other Alternatives
If the goal is to check if an HTML element has a certain class, other alternatives could include:
element.getAttribute('class') == 'your-class-name'
: This method uses the getAttribute()
method to retrieve the value of the class
attribute and compares it with the target class name.However, these alternatives may not be as efficient or reliable as using the native Web APIs (classList.contains()
) in modern browsers.