<div class="test">Test</div>
var test = document.getElementsByClassName('test');
test.innerHTML;
var test = document.querySelector('.test');
test.innerHTML;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Query by class | |
QuerySelector |
Test name | Executions per second |
---|---|
Query by class | 2419900.5 Ops/sec |
QuerySelector | 2629698.8 Ops/sec |
This benchmark tests the performance of two methods for selecting HTML elements in JavaScript: document.getElementsByClassName()
and document.querySelector()
.
Options Compared:
document.getElementsByClassName('test')
: This method returns a live HTMLCollection of all elements with the class "test". It can be slow for large sets of elements because it iterates through all elements on the page to find matching ones. document.querySelector('.test')
: This method returns the first element that matches the specified CSS selector (in this case, ".test"). It is generally faster than getElementsByClassName()
because it uses a more efficient algorithm for traversing the DOM tree.Pros and Cons:
Method | Pros | Cons |
---|---|---|
getElementsByClassName() |
Returns all matching elements | Slower, especially for large sets |
querySelector() |
Faster, more efficient | Returns only the first match |
Other Considerations:
getElementsByClassName()
. If you only need the first matching element, use querySelector()
. Alternatives:
querySelectorAll()
: Similar to querySelector()
, but returns a NodeList of all matching elements. This might be a better choice if you need multiple matches but still want a relatively performant option.Let me know if you have any other questions!