Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which jQuery selection is more efficient?

Which set of selectors is more efficient?

1

$('#parent_element span.class1').do_something1();
$('#parent_element span.class2').do_something2();
$('#parent_element span.class3').do_something3();
$('#parent_element span.class4').do_something4();

2

$parent_element = $('#parent_element'); 
$parent_element.find('span.class1').do_something1();
$parent_element.find('span.class2').do_something2();
$parent_element.find('span.class3').do_something3();
$parent_element.find('span.class4').do_something4();

My guess is #2 is more effecient as it begins a search find() focused on the parent element vs the entire DOM. Is this true?

If so how many calls to that parent element would be needed to make it more efficient than #1?

Thanks!

like image 506
iambriansreed Avatar asked Dec 04 '25 22:12

iambriansreed


1 Answers

Solution #2 is wildly more efficient. Caching selectors in jQuery is one of the best ways to cut down on the time it takes to do selections. For any uses greater than 1, go with solution 2.

like image 96
Paolo Bergantino Avatar answered Dec 07 '25 12:12

Paolo Bergantino



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!