<div class="test" id="test"></div>
/*When writing async/deferred tests, use `deferred.resolve()` to mark test as done*/
const testElement = document.querySelector(".test");
const [testElement] = document.getElementsByClassName(".test");
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
querySelector | |
getElementsByClassName with destructuring assignment |
Test name | Executions per second |
---|---|
querySelector | 28673496.0 Ops/sec |
getElementsByClassName with destructuring assignment | 15922849.0 Ops/sec |
The provided benchmark compares two methods of selecting DOM elements in JavaScript: document.querySelector
and document.getElementsByClassName
, the latter using destructuring assignment.
document.querySelector
:
const testElement = document.querySelector(".test");
document.getElementsByClassName
using destructuring assignment:
const [testElement] = document.getElementsByClassName(".test");
document.querySelector
Pros:
Cons:
getElementsByClassName
for multiple elements since it involves parsing the CSS selector and can involve more overhead.document.getElementsByClassName
Pros:
Cons:
querySelector
is significantly faster in this specific instance, with approximately 28.7 million executions per second compared to around 15.9 million for getElementsByClassName
with destructuring.document.getElementById
: If you're specifically looking for an element by ID, this method is the fastest as IDs are unique in a document.document.querySelectorAll
: Similar to querySelector
, but returns a NodeList of all matching elements, useful for case handling multiple elements.Overall, the choice between these methods depends on your specific use case, particularly considerations of performance versus flexibility in selector usage.