<script src="//code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<div id="fixed-id"></div>
var el = document.getElementById("fixed-id");
var className = el.className;
var el = document.querySelector('#fixed-id');
var className = el.className;
var el = document.querySelectorAll('#fixed-id');
var className = el.className;
var el = $("#fixed-id");
var className = el.className;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Vanilla getElementById(id) | |
Vanilla querySelector(#id) | |
Vanilla querySelectorAll(#id) | |
jQuery(#id) |
Test name | Executions per second |
---|---|
Vanilla getElementById(id) | 4277035.5 Ops/sec |
Vanilla querySelector(#id) | 3103198.5 Ops/sec |
Vanilla querySelectorAll(#id) | 904798.1 Ops/sec |
jQuery(#id) | 3267010.5 Ops/sec |
Let's dive into the explanation of the benchmark and its options.
Benchmark Definition The benchmark is designed to compare the speed of retrieving an element by ID using two approaches: jQuery and Vanilla JavaScript.
Options Compared
getElementById
: This method uses the document.getElementById()
function, which returns the first element with the specified ID.querySelector
: This method uses the document.querySelector()
function, which returns the first element that matches the specified CSS selector.querySelectorAll
: This method uses the document.querySelectorAll()
function, which returns a NodeList of all elements that match the specified CSS selector.$
function to select the element with the specified ID.Pros and Cons
getElementById
:querySelectorAll
) or suitable for complex queries.querySelector
:getElementById
, allowing for more complex CSS selectors. Can also be used to retrieve multiple elements at once.getElementById
due to the complexity of the selector.querySelectorAll
:getElementById
due to the overhead of processing multiple elements.Library: jQuery
The $(
symbol is a part of the jQuery library, which provides a simplified way to interact with the DOM. In this benchmark, jQuery's $
function is used to select elements by ID.
Special JS Feature/ Syntax: #id
This is a CSS selector notation that selects an element by its ID. It is not specific to any particular JavaScript library or feature.
Other Alternatives
querySelector
with attribute selectors: Instead of using the id
attribute, you can use other attribute selectors like [attribute="value"]
or [attribute ~='value']
.style
, class
, or content-attr
.In summary, this benchmark provides a straightforward comparison of four methods for retrieving an element by ID: Vanilla JavaScript's getElementById
, querySelector
, and querySelectorAll
methods, and jQuery's $
function. The results can help users understand the performance differences between these approaches and make informed decisions about which method to use depending on their specific use case.