<div id="testdiv">
<div id="unique" class="unique" name="unique" data-unique="1">test</div>
</div>
var i, imax;
var doc = document;
var test = doc.getElementById('testdiv').childNodes[0].innerHTML;
var formelem = doc.getElementById('testdiv').getElementsByTagName('div')[0].innerHTML;
var test = doc.getElementById('testdiv').querySelector('.unique').innerHTML;
var test = doc.getElementById('testdiv').getElementsByClassName('unique')[0].innerHTML;
var test = doc.getElementsByName('unique')[0].innerHTML;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
getElementById | |
getElementsByTagName | |
querySelector | |
getElementsByClassName | |
getElementsByName |
Test name | Executions per second |
---|---|
getElementById | 16986594.0 Ops/sec |
getElementsByTagName | 7044473.5 Ops/sec |
querySelector | 9376042.0 Ops/sec |
getElementsByClassName | 6684191.0 Ops/sec |
getElementsByName | 9977413.0 Ops/sec |
What is being tested?
MeasureThat.net is testing the performance of different methods to retrieve a single DOM element in JavaScript. The benchmark compares the execution speed of four methods:
getElementById
querySelector
getElementsByClassName
getElementsByName
Each method is used to access an element with a specific id, class, or name.
Options compared:
The benchmark directly compares the performance of these four methods.
Pros and Cons of each approach:
getElementById
:querySelector
:getElementById
, allows for more complex selectors.getElementsByClassName
:getElementsByName
:Libraries and their purposes:
querySelector
: This is a CSS selector API that allows you to select elements based on various criteria (e.g., id, class, attributes). It's part of the W3C DOM specification.getElementsByClassName
: This method returns a NodeList containing all elements with the specified class name.Special JS features or syntax:
querySelector
and getElementsByClassName
use CSS selectors, which are a powerful feature in JavaScript for selecting elements.getElementsByName
method uses the name
attribute to search for elements, which might not be as common as other attributes like id
or class
.Other alternatives:
document.getElementById
with a fallback: In some cases, using document.getElementById
and then checking if the result is null can provide better performance than directly using getElementsByClassName
.document.querySelectorAll
(for all elements matching the selector) or Array.prototype.filter
and Element.prototype.matches
(for complex selections).