<div id="foo" class="bar baz"></div>
var test_element = document.getElementById("foo");
test_element.hasAttribute('class');
test_element.classList.contains("bar");
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Use hasAttribute shorthand | |
Use classList |
Test name | Executions per second |
---|---|
Use hasAttribute shorthand | 69020768.0 Ops/sec |
Use classList | 36945008.0 Ops/sec |
Let's break down the JavaScript microbenchmark on MeasureThat.net.
Benchmark Definition
The benchmark compares two approaches for checking if an HTML element has a specific CSS class: using the hasAttribute
shorthand and using the classList.contains()
method.
Script Preparation Code
This code creates a variable test_element
that represents an HTML element with the id "foo". This element is assumed to have some CSS classes attached to it, but their names are not specified.
Html Preparation Code
This code generates an HTML string that contains a <div>
element with the id "foo" and two classes: "bar" and "baz".
Options Compared
The benchmark compares two options:
hasAttribute('class')
: This method checks if the class
attribute of the element is set to a non-empty value. It's an older way of checking for CSS classes, but it has some drawbacks (see below).classList.contains('bar')
: This method checks if the bar
class is present in the element's class list. It's a more modern and efficient way of checking for CSS classes.Pros and Cons
hasAttribute('class')
:class
attribute is set to a non-empty value, not if it's actually a valid class name (e.g., " foo").classList.contains()
for larger class lists.classList.contains('bar')
:classList
property, which is not supported in older browsers.Library
In this benchmark, no specific library is used beyond what's built into JavaScript (e.g., DOM APIs). However, if you were to use a third-party library like jQuery or Lodash, you might find more convenient methods for working with CSS classes.
Special JS Feature/Syntax
This benchmark uses the classList
property, which is a relatively modern feature introduced in ECMAScript 2015 (ES6). It's not supported in older browsers, so if you need to support those, you should use one of the other approaches. The contains()
method is also supported by modern JavaScript engines.
Other Alternatives
If you don't want to use classList.contains()
, you could also use a custom function to check for class presence:
function hasClass(element, className) {
return element.className.indexOf(className) !== -1;
}
Keep in mind that this approach can be slower and less efficient than using classList.contains()
.
Overall, the benchmark suggests that using classList.contains()
is a good choice for checking CSS class presence in modern browsers.