<div id="testElement" name="testElem"></div>
var el = document.getElementById('testElement');
var className = el.className;
var el = document.querySelector('#testElement');
var className = el.className;
var el = document.getElementsByName('testElem');
var className = el.className;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
getElementById | |
querySelector | |
getElementsByName |
Test name | Executions per second |
---|---|
getElementById | 5868315.5 Ops/sec |
querySelector | 3360567.8 Ops/sec |
getElementsByName | 5939290.5 Ops/sec |
Benchmark Overview
The provided benchmark measures the performance of three JavaScript methods to access an HTML element: document.getElementById()
, document.querySelector()
, and document.getElementsByName()
.
Method Comparison
document.getElementById()
: This method returns the first element with the specified ID in the document. If no element is found, it returns null
.null
if no element is found.document.querySelector()
: This method returns the first element that matches the specified CSS selector in the document.getElementById()
, as it allows for more complex selectors.getElementById()
.document.getElementsByName()
: This method returns a NodeList containing all elements with the specified name attribute value in the document.querySelector()
if the element is found in the first iteration of the DOM traversal.querySelector()
, as it only searches for elements by name, not CSS selectors.Library and Special JS Features
None of the benchmark cases use a specific JavaScript library. However, they do demonstrate basic HTML and CSS concepts.
No special JavaScript features or syntax are used in these test cases.
Other Alternatives
If you need to access an HTML element, consider the following alternatives:
document.querySelector()
with a more complex CSS selector.$()
, .class()
).In general, the choice of method depends on the specific requirements of your application. If you need to access an element by its ID, document.getElementById()
is usually a good choice. For more complex scenarios, querySelector()
may be a better option.