Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QuerySelector of javascript VS Find() of Jquery

On performance basics QuerySelector() of javascript or Find() of Jquery which is better to use in code on factors like speed and efficent access to Dom Elements

element = document.querySelector(selectors);

or

element= $(document).find(selectors);
like image 780
Sivaprakash B Avatar asked Oct 30 '25 19:10

Sivaprakash B


1 Answers

querySelector is far more performant. It doesn't require a library nor the construction of a jQuery object.

Warning, the following will block your browser for a little bit, depending on your computer's specs:

const t0 = performance.now();
for (let i = 0; i < 1e6; i++) {
  const div = document.querySelector('div');
}
const t1 = performance.now();
for (let i = 0; i < 1e6; i++) {
  const div = $(document).find('div');
}
const t2 = performance.now();

console.log('querySelector: ' + (t1 - t0));
console.log('jQuery: ' + (t2 - t1));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>some div</div>

That said, performance for selecting a single element will rarely matter - I think it would only be something to consider if it's done in a nested loop, for example, and is done thousands of times in under a second.

like image 105
CertainPerformance Avatar answered Nov 01 '25 08:11

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!