Which set of selectors is more efficient?
$('#parent_element span.class1').do_something1();
$('#parent_element span.class2').do_something2();
$('#parent_element span.class3').do_something3();
$('#parent_element span.class4').do_something4();
$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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With