JQuery caching elements, difference between $ variable and variable?
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();
// ...
source to share
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
source to share