Does the jQuery element store in var cause the element to re-search when used?

So I have JavaScript / jQuery that looks like this:

var $foo = $('#bar'); $foo.hide(); 

I worked under the assumption that jQuery runs on this selector and stores the resulting DOM element in var $foo ... which, as far as I can see, is right.

However, does calling $foo.hide() jQuery call again to search for the #bar element?

+6
source share
2 answers

No, this is not so, the link is made when calling $ (elem). This is why var used to store a reference to an element. It is always better to store references to var , so the following temporary code is used, the old link is used, and there is no need to look for the DOM again.

 //reference var a = $('#id'); //use a.hide(); //same reference, use again a.show(); 
+8
source

From my understanding, setting the jQuery object to var caches the object, and therefore it will not rebuild the jQuery object every time you need to use it to do somehting.

A few articles about this, here is the first I found google

I think, however, $('#bar') refers directly to document.getElementById ('bar'), so it doesn't build too much and therefore is pretty fast, but faster when you have an array of objects. $('.class tagType')

+1
source

All Articles