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?
No 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();