Black friday

Save big!

All courses under $5 - for a limited time!

Code has been added to clipboard!

Make Your Code Run Faster with jQuery Chaining

Reading time 2 min
Published Dec 19, 2017
Updated Oct 1, 2019

Using multiple jQuery statements in our codes means constantly reaccessing the same elements and reusing the same selectors most of the time. Doing that slows down the execution of your code.

To avoid that, we may use jQuery chaining. As the name itself suggests, its main function is chaining methods together into one statement.

By using a chained jQuery statement, you will save server time, as the script will load much faster. Moreover, you will also be saving your own time, as it is always easier and quicker to read neat and compact code. Chaining in jQuery is easy and practical - let's see how it's done with some simple examples.

jQuery Chaining: Main Tips

  • We normally write statements which run one after another as separate operations.
  • jQuery method chaining allows operations to be executed more quickly by connecting multiple methods in a single statement.
Theory is great, but we recommend digging deeper!

Definition and Examples

jQuery chaining allows you to execute multiple methods in a single statement. By doing that, it removes the need for repeatedly finding the same element to execute code. It also makes the code more compact and readable.

To perform jQuery method chaining, you should append actions to one another.

See an example of a chained jQuery statement below. Keep in mind that even at this point, more method calls could be added:

Example
$("#par").css("color", "blue").slideUp(2500).slideDown(2500);

Due to long, chained jQuery statements, the lines of code can become hard to read. Luckily, the syntax is not very strict. Breaking lines will not break the chain jQuery statement:

Example
$("#p1").css("color", "blue")
 .slideUp(2500)
 .slideDown(2500);

jQuery Chaining: Summary

  • Traditionally, each statement is run as a separate operation. Chaining in jQuery is used to link multiple statements together.
  • A chained jQuery statement is executed as one operation. Therefore, it runs faster.