<ul id="list" class="c_list"><li class="li"></li></ul>
document.querySelector(".c_list li");
document.getElementById('list').getElementsByClassName('li');
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
query | |
id |
Test name | Executions per second |
---|---|
query | 1663465.4 Ops/sec |
id | 1824503.0 Ops/sec |
Let's break down what is being tested in this benchmark.
The benchmark is comparing the performance of two different methods to select elements from an HTML list: document.querySelector()
and document.getElementById().getElementsByClassName()
.
Method 1: document.querySelector()
This method uses a CSS selector to find the element. In this case, it's selecting all li
elements inside the .c_list
class. The querySelector() function returns a single value if found or null if not found, which is why it's often used when you only expect one match.
Pros:
Cons:
Method 2: document.getElementById().getElementsByClassName()
This method first finds an element by its ID (document.getElementById('list')
) and then gets all elements with a specific class name (getElementsByClassName('li')
). This method returns an HTMLCollection, which is an array-like object containing the matched elements.
Pros:
Cons:
Other considerations
Library and special JS feature
Neither of these methods uses a library, but it does use standard JavaScript features:
document
is a global object that represents the HTML document.querySelector()
and getElementsByClassName()
are part of the DOM API.Alternatives
Some alternative methods for selecting elements in JavaScript include:
document.querySelectorAll()
: Returns an HTMLCollection containing all matching elements, similar to getElementsByClassName().document.querySelectorAll()
: Returns a NodeList containing all matches, which can be converted to an array-like object.RegExp
objects and string manipulation to select elements based on patterns.However, these alternatives might not offer significant performance benefits over the two methods being compared in this benchmark.