I always save the result of the find()
in order to avoid multiple sub tree traversal if I need the value several times:
var $a_bar = $('div.foo').find('a.bar');
$a_bar.removeClass(...);
// ... code here
$a_bar.bazz();
instead of
$('div.foo').find('a.bar').removeClass(...);
// ... code here
$('div.foo').find('a.bar').bazz();
I am wondering if it is not a micro-optimization... So what is the cost/complexity of finding a node in JQuery
?
jQuery find() Method The find() method returns descendant elements of the selected element. A descendant is a child, grandchild, great-grandchild, and so on. The DOM tree: This method traverse downwards along descendants of DOM elements, all the way down to the last descendant.
ready(function() { $('#list li'). click(function() { alert($(this). attr("id")); alert($(this). text()); }); });
The jQuery selector finds particular DOM element(s) and wraps them with jQuery object. For example, document. getElementById() in the JavaScript will return DOM object whereas $('#id') will return jQuery object.
You can test it on js perf : http://jsperf.com/ Just create a test and run it.
I have created a small test here : http://jsperf.com/jquery-find55
On my browser (firefox 18) :
So, yes, find
is "slow" and it's definitively a good idea to store it in a variable.
If you are going to be re-using variables multiple times, it is definitely a great idea to cache
them like you are doing.
.find()
traversing within the jQuery object you pass before it, so it only looks within what is already given, making it very fast.
var $mainElement = $('#whatever'),
$innerLIs = $mainElement.find('li'),
$innerTDs = $mainElement.find('td');
// Now that these are cached in memory, doing anything to them is very quick
$innerLIs.hide();
// etc etc
If we kept querying for them, it would have to look through the DOM each time. And once that was finished, it would be wrapping it in a jQuery object each time as well.
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