JQuery caching elements, difference between $ variable and variable?
I was wondering if anyone could explain the difference in element caching in JQuery. One with and without a dollar sign.
Here's an example:
var cached = $('.someElement');
var $cached = $('.someElement');
There is no difference . Both are cached, but only the variable name is different.
Both cached
and $cached
are valid variables Javascript:
var $message = 'Hello';
var message = 'Hello';
The $ variable syntax is often used to indicate that a variable contains a jQuery object and not another type (string, integer, DOM element, ...). It's a kind of Hungarian notation, but it's just a convention among programmers. Nothing Javascript or jQuery overlays.
When people talk about caching a jQuery variable, they only mean doing the search once :
//Like this: cached: search is done once.
var clientSpan = $('#client');
clientSpan.hide();
clientSpan.show();
// ...
//Not like this: uncached
$('#client').hide();
$('#client').show();
// ...
The prefix is $
used to denote that the variable contains a jQuery object. In terms of code, there is no difference, both elements in your example are now contained in a jQuery object inside each variable.
For example:
var myVariable = $("#myElement").text(); // string
var $myVariable = $("#myElement"); // jQuery object