<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
<div id="testElement" class="test class list classes"></div>
var el = $("#testElement")[0];
var el = document.getElementById('testElement');
var el = document.querySelector("#testElement");
var el = $(document.getElementById('testElement'));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
jQuery | |
getElementById | |
querySelector | |
$(getElementById) |
Test name | Executions per second |
---|---|
jQuery | 4639122.0 Ops/sec |
getElementById | 10660162.0 Ops/sec |
querySelector | 2877241.5 Ops/sec |
$(getElementById) | 4340357.5 Ops/sec |
Let's dive into the explanation of what's being tested in this benchmark.
Benchmark Purpose
The goal of this benchmark is to compare the performance of three different approaches for retrieving an HTML element by its ID:
$(
and )
syntax)document.getElementById()
function)document.querySelector()
function)Additionally, a variation of jQuery ($(document.getElementById('testElement'))
) is also included in the benchmark.
Options Compared
Here's what's being compared:
$
symbol and its shorthand for document.getElementById()
, querySelectorAll()
, etc.document.getElementById()
functiondocument.querySelector()
functionThe comparison is done between these two approaches, with each approach having a variation that uses jQuery's syntax.
Pros and Cons of Each Approach
Here are some pros and cons for each approach:
document.getElementById()
due to its CSS-like syntax; supports modern features like attribute selectors.Library Used in Test Cases
In this benchmark, jQuery is used as a library, specifically version 3.6.3. The $(
and )
symbols are used to access its methods, such as getElementById()
.
Special JavaScript Feature or Syntax
There's no special JavaScript feature or syntax being tested in this benchmark. All the approaches use standard JavaScript features and syntax.
Other Alternatives
If you're interested in alternative approaches for retrieving elements by ID, some options include:
getElementById()
or querySelector()