how does jquery chaining work?

Solution 1:

If you have an object with certain methods, if each method returns an object with methods, you can simply call a method from the object returned.

var obj = {   // every method returns obj---------v
    first: function() { alert('first');   return obj; },
    second: function() { alert('second'); return obj; },
    third: function() { alert('third');   return obj; }
}

obj.first().second().third();

DEMO: http://jsfiddle.net/5kkCh/

Solution 2:

All that it is doing is returning a reference to this when the method finishes. Take this simple object for example:

 var sampleObj = function()
 {
 };

 sampleObj.prototype.Foo = function()
 {
     return this;
 };

You could chain these calls all day because you return a reference to this:

var obj = new sampleObj();
obj.Foo().Foo().Foo().Foo() // and so on

jQuery simply performs an operation, then returns this.

Solution 3:

Basically the first function call $('myDiv') returns a jQuery object, then each subsequent call returns the same one.

Loosely,

var $ = function(selector) {
   return new jQuery(selector);
};

jQuery.prototype.removeClass = function(className) {
   // magic
   return this;
}

Solution 4:

return $this;

each jQuery function returns an instance of the jQuery class, which can then have methods called on it. you could break it down, and this code would have the same effect.

jQuery_obj = $('myDiv');
jQuery_obj = jQuery_obj.removeClass('off');
jQuery_obj = jQuery_obj.addClass('on');