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

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);

Leave a Comment