<div id="id1" class="cl2">
<span>some text</span>
</div>
document.getElementById("id1");
document.querySelector(".cl2");
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
id | |
class |
Test name | Executions per second |
---|---|
id | 8330404.0 Ops/sec |
class | 5009300.0 Ops/sec |
Let's break down what's being tested and compared in this benchmark.
Benchmark Description
The benchmark is called "class vs id test 3". It compares two ways of selecting an HTML element using JavaScript:
document.getElementById("id1");
document.querySelector(".cl2");
Test Cases
There are two individual test cases:
document.getElementById("id1");
to select an HTML element.document.querySelector(".cl2");
to select an HTML element.querySelector()
and CSS selector syntaxComparison
The benchmark measures the execution time per second for each test case. The results show that:
Pros and Cons
Here's a brief summary of each approach:
document.getElementById()
document.querySelector()
getElementById()
, can be less efficient for large documents.Other Alternatives
If you need to select an HTML element by its class attribute, you can use other methods:
document.getElementsByClassName()
: Returns a list of elements with the specified class name.querySelectorAll()
: Similar to querySelector()
, but returns a NodeList of matching elements.Keep in mind that these alternatives might have different performance characteristics and are not directly compared in this benchmark.