<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.js'></script>
<div>
<ul id="menu">
<li class="menu-item">
</li>
<li class="menu-item">
</li>
<li class="menu-item">
</li>
<li class="menu-item">
</li>
</ul>
</div>
const elem = $(".menu-item");
if ($(document.querySelectorAll(".test")).css("opacity") == "0.2")
$(document.querySelectorAll(".test")).css("opacity", "1");
else $(document.querySelectorAll(".test")).css("opacity", "0.2");
if ($(".test").css("opacity") == "0.2") $(".test").css("opacity", "1");
else $(".test").css("opacity", "0.2");
if ($(elem).css("opacity") == "0.2") $(elem).css("opacity", "1");
else $(elem).css("opacity", "0.2");
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
querySelectorAll | |
$(".class") | |
$(elem) |
Test name | Executions per second |
---|---|
querySelectorAll | 324032.4 Ops/sec |
$(".class") | 232215.9 Ops/sec |
$(elem) | 31191.8 Ops/sec |
The benchmark illustrated in the JSON primarily compares three different methods of selecting DOM elements and manipulating their CSS properties using jQuery, a widely-used JavaScript library for simplifying HTML document traversing, event handling, and animation. The specific tests being compared are:
querySelectorAll
as a jQuery selector:
querySelectorAll
if ($(document.querySelectorAll(".test")).css("opacity") == "0.2") $(document.querySelectorAll(".test")).css("opacity", "1"); else $(document.querySelectorAll(".test")).css("opacity", "0.2");
document.querySelectorAll
method to find elements by class and then applies a jQuery method to manipulate the CSS opacity property.Selecting elements by jQuery class selector:
$(".class")
if ($(".test").css("opacity") == "0.2") $(".test").css("opacity", "1"); else $(".test").css("opacity", "0.2");
Using a pre-selected jQuery element reference:
$(elem)
if ($(elem).css("opacity") == "0.2") $(elem).css("opacity", "1"); else $(elem).css("opacity", "0.2");
elem
(which contains the jQuery selection of elements with class "menu-item") is used to manipulate the opacity.Using querySelectorAll
:
Using jQuery class selector:
Using cached jQuery reference:
In addition to the methods tested, developers can also consider:
document.querySelector
or document.getElementsByClassName
: For similar performance as querySelectorAll
without the jQuery overhead.element.style.opacity
can further improve performance, eliminating the need for jQuery entirely in modern web applications given that native features are well-optimized in browsers.The benchmark results demonstrate performance variances between the approaches, showing that using querySelectorAll
(324032.44 Executions/Second) is the most efficient, followed by jQuery's class selector (232215.92 Executions/Second), and ultimately the pre-selected jQuery reference (31191.83 Executions/Second).
When deciding which approach to use, developers should take into account: