Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

jQuery chaining

jQuery - Chaining


With jQuery, you can chain actions/methods together.

Chaining lets us run multiple jQuery methods in one statement (on the same element).


jQuery method chaining

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

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

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

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

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

Example

$

(

"

#p1

"

)

.

css

(

"

color

"

,

"

red

"

)

.

slideUp

(

2000

)

.

slideDown

(

2000

)

;

Try it »

We can also add multiple method calls if needed.

**Tip:** When chaining, lines of code can get very long. However, jQuery syntax is not very strict; you can format it as you like, including line breaks and indentation.

Writing it like this also works fine:

Example

$

(

"

#p1

"

)

.

css

(

"

color

"

,

"

red

"

)

.

slideUp

(

2000

)

.

slideDown

(

2000

)

;

Try it »

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