In jQuery, what is the difference between $ and $.? Please provide a practical explanation if possible.
- 14,650
- 21
- 72
- 105
- 57,511
- 78
- 272
- 425
5 Answers
$ is a reference (or synonym, if you want an analogy) to the global jQuery object. $.<method> calls a static method of the jQuery object, where $(<selector>) creates a new instance of the jQuery object.
- 16,462
- 6
- 50
- 83
In the context of jQuery, $ refers to the global jQuery object.
$. by itself is invalid JavaScript. As $ is an object, methods on this object are called like on any other object: $.methodname().
Maybe it becomes clearer by substituting $ with jQuery: jQuery.methodname().
- 795,719
- 175
- 1,089
- 1,143
I presume you are asking about the syntactic difference between $('#selector'); and $.parseJSON(str);.
The former is an invocation of a function called $ and the latter invokes it's method called parseJSON. Yup, functions can have methods - it is possible because Javascript functions are also objects. Figuratively speaking:
<script type="text/javascript">
function $(str) {
alert(str);
}
$.parseJSON = function () {
alert('Parsing JSON');
}
$('Hi');
$.parseJSON('{}');
</script>
- 17,973
- 8
- 64
- 88
$ - dollar sign is also same as Jquery usage. But I preferred to use dollar sign because I like the way dollar sign is.
- 1,527
- 2
- 10
- 22
-
The question is about the difference between `$` and `$.`, not `$` and `jQuery`. – JJJ May 16 '13 at 05:39
From http://en.wikipedia.org/wiki/JQuery:
the $ function, which is a factory method for the jQuery object. These functions, often called commands, are chainable; they each return a jQuery object
$.-prefixed functions. These are utility functions which do not work on the jQuery object per se.
Typically, access to and manipulation of multiple DOM nodes begins with the $ function being called with a CSS selector string, which results in a jQuery object referencing matching elements in the HTML page. This node set can be manipulated by calling instance methods on the jQuery object, or on the nodes themselves. For example:
$("div.test").add("p.quote").addClass("blue").slideDown("slow");This line finds the union of all div tags with class attribute test and all p tags with CSS class attribute quote, adds the class attribute blue to each matched element, and then slides them down with an animation. The $ and add functions affect the matched set, while the addClass and slideDown affect the referenced nodes.
The methods prefixed with $. are convenience methods or affect global properties and behaviour. For example, the following is an example of the map function called each in jQuery:
$.each([1,2,3], function(){ document.write(this + 1); });This writes the number 234 to the document.