<div class="test"></div>
document.querySelectorAll(".test")
document.getElementsByClassName("test")
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
querySelectorAll | |
getElementsByClassName |
Test name | Executions per second |
---|---|
querySelectorAll | 1973743.1 Ops/sec |
getElementsByClassName | 8988729.0 Ops/sec |
Let's dive into the details of this benchmark.
What is being tested?
The benchmark compares two methods for selecting HTML elements on a web page:
document.querySelectorAll(".test")
document.getElementsByClassName("test")
In other words, it tests how long it takes to retrieve all elements with a specific class name ("test"
).
What options are compared?
There are only two test cases in this benchmark:
querySelectorAll
API, which returns a NodeList of all elements that match the specified selector (in this case, an element with class "test"
).getElementsByClassName
API, which also returns a HTMLCollection of all elements that have the specified class name.Pros and Cons:
Here's a brief summary:
Library and purpose
No external libraries are used in this benchmark. The two methods being compared are part of the standard JavaScript API.
Special JS feature or syntax
There's no special JavaScript feature or syntax involved in this benchmark. Both methods use standard DOM APIs.
Alternatives
If you need to select multiple elements with specific class names, here are some alternatives:
querySelectorAll
and specify a selector that targets all classes (e.g., .test ~ .another-class
). This method is more flexible than using separate calls to getElementsByClassName
.document.querySelectorAll("...")
) with more advanced selectors (e.g., attribute selectors).That's it! I hope this explanation helps software engineers understand the pros and cons of these two methods.