<div id="testElement">
<div class="testElementChild"></div>
<div class="testElementChild"></div>
<div class="testElementChild"></div>
<div class="testElementChild"></div>
<div class="testElementChild"></div>
</div>
var el = document.getElementById('testElement');
var children = el.getElementsByClassName('testElementChild');
var length = children.length;
var el = document.querySelector('#testElement .testElementChild');
var length = el.length;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
getElementById + getElementByClass | |
querySelector |
Test name | Executions per second |
---|---|
getElementById + getElementByClass | 40607756.0 Ops/sec |
querySelector | 8496120.0 Ops/sec |
Let's dive into the explanation of the provided JSON benchmark.
Benchmark Definition
The test compares two approaches for selecting elements in HTML documents:
getElementById + getElementByClassName
(or, more accurately, getElementsByTagName
followed by getElementsByClassName
)querySelector
What are we testing?
We're measuring the performance of these two methods on a specific HTML document with multiple child elements.
Options compared
The options being compared are:
document.getElementById
and then el.getElementsByClassName
to get all elements with a specific class.document.querySelector
to select an element based on a CSS selector (in this case, #testElement .testElementChild
).Pros and Cons of each approach
getElementById + getElementByClassName
, especially for larger datasets.Library/Tool usage
In this benchmark, querySelector
is implemented by the browser's JavaScript engine. However, if you're using a library like jQuery, you might use its $(selector)
equivalent to select elements.
Special JS feature/syntax
None are mentioned in this benchmark.
Other alternatives
Additional approaches for selecting elements include:
getElementsByTagName
and then filtering the results.querySelectorAll
(similar to querySelector
, but returns all matching elements).Benchmark preparation code
The provided HTML document contains an <div>
element with the ID testElement
and multiple child elements with the class testElementChild
. The JavaScript script prepares two variables: el
(the selected element) and children
(an array of child elements).
Individual test cases
There are two test cases:
getElementById + getElementByClass
: This test case uses document.getElementById
to select the testElement
and then getElementsByClassName
to get all child elements with the class testElementChild
.querySelector
: This test case uses document.querySelector
to select an element based on a CSS selector (#testElement .testElementChild
) and then retrieves its length.The benchmark results show the number of executions per second for each test case, indicating their relative performance on this specific HTML document.