jQuery syntax - when to use $ (dollar) vs jQuery [duplicate]

Solution 1:

They both do the same thing. Most Libraries use $ as a shorter way to access functions within the libraries.

jQuery has many ways of accessing its library:

window.jQuery('#SPANID').html("Some Text");

window.$('#SPANID').html("Some Text");

jQuery('#SPANID').html("Some Text");

$('#SPANID').html("Some Text");

jQuery or window.jQuery can be used instead of $ if you were using more than one library.

JQuery has a function called jQuery.noConflict(); which relinquishs jQuery's control of the $ variable making $ not work with jQuery.

This would be good for using more than one library that use $.

So you when you use jQuery you would do jQuery('#message').addClassName('read'); and $('#message').addClassName('read'); when using Prototype.

(This next bit is a little off topic but will help if you want to use $ with multiple libraries)

Although there is a way to use $ on different libraries at the same time, using anonymous functions. like so:

(function($){


})(jQuery);


(function($){


})(Prototype);

Each of the functions passes the library object, so jQuery and Prototype, as the variable $ allowing use to use it with many libraries. If you contain your code for each library within each one it will work.

For example:

(function($){
    $(document).ready(function(){

         $('#message').addClass('read');

    });

})(jQuery);


(function($){
     document.observe("dom:loaded", function() {

         $('message').addClassName('read');
         //Or
         $$('#message').addClassName('read');

     });

})(Prototype);

Solution 2:

if you are using more then one javascript library there can be conflicts if you just use the $. using jQuery will avoid those.

Solution 3:

It's an alias for the same thing. If you want to use jQuery on the same page as other libraries that use the $ symbol, you can use jQuery with the .noConflict() option. This will allow you to use $ for the other library and jQuery for the jQuery library.