So, I have some JavaScript/jQuery that looks like this:
var $foo = $('#bar');
$foo.hide();
I've been operating under the assumption that jQuery operates on the given selector, and saves the resulting DOM element to the var $foo
...which, as far as I can see is true.
However, does invoking $foo.hide()
cause jQuery to re-seek the #bar
element?
So, I have some JavaScript/jQuery that looks like this:
var $foo = $('#bar');
$foo.hide();
I've been operating under the assumption that jQuery operates on the given selector, and saves the resulting DOM element to the var $foo
...which, as far as I can see is true.
However, does invoking $foo.hide()
cause jQuery to re-seek the #bar
element?
- This is considered best practices. You should almost always save a reference to the jQuery object if you plan on reusing. – troynt Commented Nov 27, 2012 at 14:53
3 Answers
Reset to default 11No it doesn't, reference is made when $(elem) is called. This is why var
is used, to store reference to element. It is always best practice to store references to var
so next time code is used, old reference is used, and there is no need for searching DOM again.
//reference
var a = $('#id');
//use
a.hide();
//same reference, use again
a.show();
From my understanding, setting the jQuery object as a var, caches the object, and therefore it won't rebuild the jQuery object everytime you need to use it to execute somehting.
A few articles regarding this, here's the first one I found off google
I think however $('#bar')
refers directly to document.getElementById('bar') so, not much building and therefore fairly fast, but it's faster when you have an array of objects. $('.class tagType')
@Davor Zubak's answer is mostly correct. however, contrary to what is stated, it is not always considered best practice to store element references.
it is only best practice to store element references for as long as you know they will exist, and you will reuse them. element lookups especially by id are not particularly costly except when multiplied.
DOM contents change, and if you store an element reference to an item that is removed, and then replaced with the similar content (i.e. the same "query" would find this element now) you are storing and using a reference to an element that no longer exists and preventing garbage collection.
it is often best practice to store element references for the time that you are reusing an element within a context (which can sometimes even only be within that process tick) and refetch on the next call