jQuery - Chaining


You may link actions/methods together using jQuery.

Chaining allows us to execute many jQuery methods (on the same element) within one line or sentence.


jQuery Method Chaining

So far we wrote jQuery statements one by one (one after the other).

There is, however, a method known as chaining that allows us to perform several jQuery instructions on the same element one after the other (s).

Tip : This eliminates the need for browsers to search for the same element(s) several times.

An action is chained when it is appended to the preceding action.

Example :- The example below combines the techniques css(), slideUp() and slideDown() in a single line. The "p1" element will first be changed to red, then slid up and down.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
    $(document).ready(function () {
        $("#b1").click(function () {
            $("#p1").css("color", "red").slideUp(2000).slideDown(2000);
        });
    });
</script>
</head>
<body>

<p id="p1">jQuery is fun!!</p>

<button id="b1">Click me</button>

</body>
</html>

Output

jQuery is fun!!


Tip : The code line might be rather lengthy when chaining. JQuery is not extremely stringent with regard to syntax; you may style it how you like, including line breaks and indentations.

Example 2 :- This also works just fine:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
    $(document).ready(function () {
        $("#b3").click(function () {
            $("#p3").css("color", "red")
                    .slideUp(2000)
                    .slideDown(2000);
        });
    });
</script>
</head>
<body>

<p id="p3">jQuery is fun!!</p>

<button id="b3">Click me</button>

</body>
</html>

Output :-

jQuery is fun!!


Extra whitespace is removed by jQuery, and the lines above are executed as a single long line of code.

You can also search for these topics, selectors used in jquery chaining, working of chaining the ajax calls, jquery chaining actions and animations, working of appending jquery chaining method, addclass, autocomplete the code, use jquery chaining different elements, jquery each function chaining, how event handlers works, multiple chaining, callbacks, chaining the promises and css properties, how to implement, order declaration, example.