I’m a web developer working for a company as a fresher. I can understand most of the code examples I find online, but I’m not sure what this line does:
var $hello = $('<div class=newHello></div>');
I’m assuming it creates a jQuery variable with the value set to a blank div with the class of
newHello, but I want to be certain and understand the syntax.
Why does a dollar sign precede the variable value? I know dollar signs are used in jQuery. Can someone provide an example to help me understand this concept better?
Yes, your assumption is correct. The line of code creates a jQuery variable named
$hello and sets its value to a new div with a class of
The dollar sign before the variable name is a convention used in jQuery to indicate that the variable contains a jQuery object.
Here’s an example to help you understand better:
// select all elements with class "myClass" using jQuery and store them in a variable with a dollar sign
var $myElements = $('.myClass');
// use jQuery methods on the variable containing the jQuery object
In the example above, the
$myElements variable contains a jQuery object that represents all elements with a class of
$ preceding the variable name is just a convention to indicate that the variable contains a jQuery object.