<div class="testClass">Test TEXT here</div>
document.querySelector('div').classList
document.querySelector('div').getAttribute('class')
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
classList | |
getAttribute |
Test name | Executions per second |
---|---|
classList | 8737959.0 Ops/sec |
getAttribute | 7240810.5 Ops/sec |
I'd be happy to explain what's being tested in this benchmark.
The test is comparing two approaches to get the class
attribute of an HTML element in JavaScript:
classList
property of HTML elements, which allows you to access and manipulate the class names of an element.getAttribute()
method of the DOM element, which returns the value of a specified attribute.Here's what's being tested:
classList
and one for getAttribute
), we're measuring the execution time of both approaches on different browsers.Pros and Cons of each approach:
getAttribute()
classList
due to the interpreter overheadLibrary usage:
In this benchmark, we don't use any external libraries. The classList
property is a built-in feature of HTML elements in modern browsers.
Special JS features or syntax:
This benchmark doesn't require any special JavaScript features or syntax beyond what's available in modern browsers (ECMAScript 2015+).
Other alternatives:
If you wanted to test other approaches, here are some alternatives:
classList
versus getAttribute()
in older browsers that may not support these features.It's worth noting that the use cases where one approach might be preferred over the other depend on specific requirements, such as:
In general, when working with HTML elements, using classList
is a more modern and efficient way to access class names. However, in some cases, getAttribute()
might be a better choice due to its wider browser support or specific requirements.