Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does saving a jQuery element to a var cause the element to be re-sought upon use?

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?

like image 849
Andrew Gray Avatar asked Nov 27 '12 14:11

Andrew Gray


People also ask

What does $() return in jQuery?

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.

Does jQuery always return an array?

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.

Which method returns the element as a jQuery object?

get()Returns: Array. Description: Retrieve the elements matched by the jQuery object.

What does VAR mean in jQuery?

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).


2 Answers

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();
like image 67
Davor Zubak Avatar answered Sep 28 '22 00:09

Davor Zubak


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')

like image 23
Likwid_T Avatar answered Sep 28 '22 02:09

Likwid_T