7

In jQuery, what is the difference between $ and $.? Please provide a practical explanation if possible.

Ricardo Altamirano
  • 13,752
  • 21
  • 69
  • 104
Moshe
  • 56,717
  • 76
  • 267
  • 423

5 Answers5

7

$ 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.

nikc.org
  • 15,738
  • 6
  • 46
  • 82
2

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().

Felix Kling
  • 756,363
  • 169
  • 1,062
  • 1,111
2

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>
Saul
  • 17,666
  • 8
  • 59
  • 87
1

$ - dollar sign is also same as Jquery usage. But I preferred to use dollar sign because I like the way dollar sign is.

Olrac
  • 1,509
  • 2
  • 10
  • 22
  • The question is about the difference between `$` and `$.`, not `$` and `jQuery`. – JJJ May 16 '13 at 05:39
1

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.

nikc.org
  • 15,738
  • 6
  • 46
  • 82
Furchin
  • 21
  • 2