<div class="testElement"></div>
var el = document.getElementsByClassName('testElement');
var className = el.className;
var el = document.querySelector('.testElement');
var className = el.className;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
getElementById | |
querySelector |
Test name | Executions per second |
---|---|
getElementById | 6557815.5 Ops/sec |
querySelector | 5918104.0 Ops/sec |
Let's break down the benchmark and its options.
The provided JSON represents a JavaScript microbenchmark that compares two approaches to retrieve an element by class name: document.getElementsByClassName
(implemented as getElementById
) and document.querySelector
.
Options being compared:
document.getElementsByClassName
: This function returns a HTMLCollection object containing all elements with the specified class name. It's a legacy method introduced in early versions of JavaScript.document.querySelector
: This function returns the first element that matches the provided CSS selector.Pros and Cons of each approach:
document.getElementsByClassName
: document.querySelector
: getElementsByClassName
on some browsers.The benchmark runs multiple executions of each approach to determine which one performs better.
Library usage:
Neither document.getElementsByClassName
nor document.querySelector
uses a library explicitly, as they are part of the HTML and JavaScript APIs.
Special JS features or syntax:
There is no mention of any special JavaScript features or syntax in this benchmark. The focus is solely on comparing two basic methods for retrieving elements by class name.
Alternatives:
If you need more selective or efficient ways to retrieve elements, consider using:
document.querySelectorAll
: A cousin of querySelector
, which returns a NodeList containing all matches.Element.prototype.closest
(for getting the closest ancestor) or Element.prototype.matches
(for matching CSS selectors).Additional considerations:
When choosing between these methods, keep in mind:
getElementsByClassName
.In the context of this benchmark, both approaches are tested on Safari 13 (Desktop) and compared in terms of performance.