jQuery Chaining

Through jQuery, you can chain actions/methods.

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

jQuery Method Chaining

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

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

Tip:This way, the browser does not have to search for the same element multiple times.

To link an action, you simply append the action to the previous action.

Example 1

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

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

Try It Yourself

If necessary, we can also add multiple method calls.

Tip:When linking, the code line may become poor. However, jQuery is not very strict in syntax; you can write in the format you wish, including line breaks and indentation.

Example 2

This format can also run:

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

Try It Yourself

jQuery will discard extra spaces and execute the above code line as a single line of long code.