How jQuery Method Chaining Works Internally
Method chaining in jQuery is a design pattern that allows developers
to run multiple commands sequentially on the same selection of elements
in a single line of code. Internally, jQuery achieves this functionality
through object-oriented JavaScript principles, primarily by returning
the calling jQuery instance—referenced by the this
keyword—from its methods, and managing the DOM element stack during DOM
traversal operations via an internal method called
pushStack().
The Core Mechanism: Returning
this
At its simplest level, chaining works because mutator methods return
the instance of the object they were called upon. In jQuery, methods are
attached to jQuery.prototype (aliased as
jQuery.fn). When an instance method executes, the
JavaScript runtime binds the this keyword to the current
jQuery object.
A typical jQuery mutator method follows this pattern:
jQuery.fn.highlight = function() {
// Perform operations on the matched elements
this.each(function() {
this.style.backgroundColor = "yellow";
});
// Return the jQuery collection itself
return this;
};By returning this, the method hands back the same jQuery
object wrapper containing the matched DOM nodes. The next chained method
immediately has access to all functions defined on
jQuery.fn.
Handling
Changing Sets: pushStack() and prevObject
Not all chained methods operate on the exact same set of elements.
Traversal methods such as .find(), .filter(),
or .parent() change the matched DOM elements. Returning the
original this in these cases would defeat the purpose of
the traversal.
To support chaining across changing element sets, jQuery uses an
internal method called pushStack():
- Creating a New Instance: When a method like
.find()locates new elements, it callsthis.pushStack(newElements). - Stack Tracking:
pushStack()instantiates a new jQuery object containing the newly matched elements. - Maintaining History: It assigns the calling jQuery
object to the new object's
prevObjectproperty (ret.prevObject = this). - Returning the New Set: The newly constructed jQuery instance is returned to the chain.
Because of this internal stack, users can call .end() to
pop the current element set off the stack and revert the chain back to
the previous set stored in prevObject.
Methods That Break the Chain
Method chaining stops when a method acts as a "getter" rather than a
"setter" or traversal operator. Methods like .text(),
.val(), .html(), or .attr(name)
(when called without a value argument) query the first element in the
collection and return raw JavaScript primitives, such as strings,
numbers, or booleans. Because the return value is no longer a jQuery
object instance, attempting to chain subsequent jQuery methods results
in a runtime TypeError.