Chaining

Allows multiple chained method calls on an object.

Most functions in jQuery are written to be chainable.



Overview


The Chaining pattern allows method calls to be chained together in a single statement. Chaining is deeply engrained in jQuery and any method that can support chaining does. In jQuery chaining is important because it limits selector processing which involves DOM traversing which can be rather slow. Here is an example of a chained jQuery statement:

$("#menu").addClass("highlight").css("margin", "2px").fadeIn("fast");

As an aside, the methods that operate on a jQuery selector set (a set of DOM elements) are commonly referred to as commands. In the above code we have three commands.

The selector selects the #menu element only once; all subsequent commands are applied to the selector's result set in a chain, one after the other.

In jQuery's code base we find numerous methods that return this or this.each which mostly represents the jQuery object which is the currently selected set of elements. Many methods use an internal helper method named jQuery.access; it has a chainable argument in which the calling method indicates whether chaining is supported or not. Here is the skeleton code of jQuery.access and its use of the chainable flag:

access: function( elems, fn, key, value, chainable, emptyGet, pass ) {

    // ...

    return chainable ? ...

}

Chaining in jQuery can also be applied to events, like so:

$("#menu").click(function (e) {
        alert("You clicked me!");
    }).mouseenter(function (e) {
        $(this).css("backgroundColor", "Red");
    }).mouseleave(function (e) {
        $(this).css("backgroundColor", "Green");
    }); 

In summary, the Chaining pattern is very important to jQuery.



Namespace