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?
When a jQuery object is passed to the $() function, a clone of the object is created. This new jQuery object references the same DOM elements as the initial one.
The jQuery function always returns a jQuery object (that is based on an array), even if there are no elements that matches the selector. That way you can always call a method that is supposed to affect the elements found, even if there are no elements that matched.
get()Returns: Array. Description: Retrieve the elements matched by the jQuery object.
The var statement declares a variable. Variables are containers for storing information. Creating a variable in JavaScript is called "declaring" a variable: var carName; After the declaration, the variable is empty (it has no value).
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();
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')
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