<div id='test'></div>
document.getElementById('test');
document.querySelector('#test');
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
by id | |
query |
Test name | Executions per second |
---|---|
by id | 5068226.5 Ops/sec |
query | 3213196.2 Ops/sec |
Let's dive into the details of this benchmark.
What is being tested?
The test case compares two different ways to select an HTML element using JavaScript:
document.getElementById('test')
(by id)document.querySelector('#test')
(query)What are these methods?
document.getElementById('test')
: This method uses the getElementById()
function to retrieve an HTML element by its ID attribute. In this case, the ID is set as "test" in the provided HTML preparation code (<div id='test'></div>
). This approach is considered a more traditional way of selecting elements.document.querySelector('#test')
: This method uses the querySelector()
function to retrieve an HTML element by its CSS selector. In this case, the selector is set as "#test", which targets the HTML element with ID "test". The querySelector()
function returns the first matching element.Pros and Cons
Here's a brief comparison of these two approaches:
What are the alternatives?
Other ways to select HTML elements in JavaScript include:
document.querySelectorAll()
(returns a NodeList containing all matching elements).document.getElementsByClassName()
, getElementsByTagName()
, and getElementsByName()
(older methods for selecting elements by class name, tag name, or element ID).These alternative methods can be useful depending on the specific use case.
Additional considerations
When working with JavaScript benchmarks, keep in mind:
That's a summary of this benchmark!