Welcome to the Treehouse Community
Looking to learn something new?
Arikaturika Tumojenko8,897 Points
How do we select elements (variables in particular) with Jquery?
I see that elements are selected using two different methods. Like this
and like this
I tried changing $overlay to $($overlay) and it seems to be working the exact same way. So what's the difference?
You are correct in that elements are selected like this:
If you are going to use this selection multiple times throughout your code, for the sanity of the developer, you create a variable so you don't have to type $('body') every time the body selection is needed.
You can create a variable out of this like this:
var body = $('body');
You can also create the variable that is prepended the $:
var $body = $('body');
Both are the right way to do it. The second construct is a way for the developer to easily look at the code and know it is a jquery object instead of a variable with a different data type. You can certainly create the variable without the $ like var body. That does not stop you from using it as a jquery object like body.append();. The $ at the beginning of the variable is for code readability. It's more of a personal preference issue.
$overlay equals $($overlay), is a redundant statement. $overlay is a variable containing an element which in this case would be like var $overlay = $('#overlay');
You could just select it like this $('#overlay') but assigning it to a variable helps with readability.
Aldo don't get confused with the jQuery dollar sign and the variable dollar sign which is just a common practice of some developers, you could just assign a variable name without the dollar sigh like this var overlay = $('#overlay');
Check out this question for more info: