Until now, we have written jQuery statements one at a time.
However, there is a technique called chaining, that allows us to run multiple jQuery commands, one after the other, on the exact same element.
This saves you time and makes your code run faster.
Chaining allows you to append multiple actions to a single selector.
Instead of making jQuery search for an element multiple times, it finds it once and executes all commands in sequence.
To chain an action, you simply append it to the previous action.
The following example chains together css(), slideUp(), and slideDown().
The paragraph element first changes to red, then slides up, and finally slides down.
$("#p1").css("color", "red").slideUp(2000).slideDown(2000);
When chaining multiple methods, the line of code can become very long and hard to read.
jQuery is not very strict on whitespace, meaning you can format chained calls with line breaks.
This keeps your code beautiful and legible.
$("#p1").css("color", "red")
.slideUp(2000)
.slideDown(2000);
Every time you write a selector like $("#p1"), the browser has to scan the entire HTML document to find it.
When you chain methods, the browser only searches the document once.
This heavily improves the performance and speed of your website.
What is the primary performance benefit of method chaining in jQuery?