jQuery - Chaining


With jQuery, you can chain actions/methods together.

Chaining allows us to run multiple jQuery methods (on the same element) within a single statement.


jQuery Method Chaining

Up until now, we have been writing one jQuery statement at a time (one after another).

However, there is a technique called chaining, which allows us to run multiple jQuery commands on the same element, one after another.

Tip:In this way, the browser does not have to repeatedly look up the same element.

To chain an action, you simply append that action to the previous action.

The following example chains together css(), slideUp(), and slideDown(). The "p1" element will first turn red, then slide up, and then slide down:

Example

$("#p1").css("color","red").slideUp(2000).slideDown(2000);

Try it Yourself »

If needed, we can also add multiple method calls.

Tip:When chaining, the line of code can become quite long. However, jQuery syntax is not very strict; you can format it however you like, including line breaks and indentation.

The following format will also work well:

Example

$("#p1").css("color","red") .slideUp(2000) .slideDown(2000);

Try it Yourself »

jQuery discards extra whitespace and executes the above code lines as one long line of code.

Other Extensions