<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.0.min.js"></script>
<div id="testElement1" class="test class list classes"></div>
<div id="testElement2" class="test classA list classes"></div>
<div id="testElement3" class="test classA list classes"></div>
let divs = $('div.classA')
let divs = document.querySelectorAll('div.classA')
let foundDivs = document.getElementsByTagName('div');
let results = [];
for(let x = 0; x < foundDivs.length; x++) {
let div = foundDivs[x];
if(div.classList.contains('classA')) {
results.push(div);
}
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
jquery | |
querySelectorAll | |
getElementsByTagName |
Test name | Executions per second |
---|---|
jquery | 755128.3 Ops/sec |
querySelectorAll | 1502281.6 Ops/sec |
getElementsByTagName | 4602002.5 Ops/sec |
Benchmark Overview
The provided JSON represents a JavaScript microbenchmark test case on MeasureThat.net, comparing the performance of three different approaches for selecting elements with a specific class:
$
functiondocument.querySelectorAll()
methoddocument.getElementsByTagName()
method followed by a custom filtering loopApproaches Compared
Each approach has its pros and cons:
$
function: Pros:document.querySelectorAll()
method: Pros:$
function.document.getElementsByTagName()
method followed by a custom filtering loop: Pros:getElementsByTagName()
.Library: jQuery
jQuery is a popular JavaScript library that simplifies DOM manipulation and event handling. Its $
function provides an easy-to-use way to select elements by class, among other selectors. The library includes various methods for selecting elements, manipulating the DOM, and responding to events.
In this benchmark, jQuery's $
function is used in its simplest form to select all <div>
elements with the class classA
.
Special JS Feature/Syntax
None mentioned.
Benchmark Preparation Code
The provided HTML preparation code includes a basic structure with three <div>
elements: <div id="testElement1" class="test class list classes"></div>
, <div id="testElement2" class="test classA list classes"></div>
, and <div id="testElement3" class="test classA list classes"></div>
. These elements are used to test the performance of each approach.
Alternatives
Other approaches for selecting elements by class include:
document.getElementsByClassName()
instead of document.querySelectorAll()
Keep in mind that the performance differences between these approaches may vary depending on the specific use case, browser, and JavaScript engine.