jQuery Chaining

Through jQuery, actions/methods can be linked together.

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


jQuery method chaining

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

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

Tip: This way, the browser doesn’t have to look for the same element multiple times.

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

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

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function()
  {
  $("button").click(function(){
    $("#p1").css("color","red").slideUp(2000).slideDown(2000);
  });
});
</script>
</head>
<body>

<p id="p1">php中文网!!</p>
<button>点我</button>

</body>
</html>

Run and try it


We can also add multiple method calls if necessary .

Tip: When linking, lines of code get messed up. However, jQuery syntax is not very strict; you can write it in the format you want, including line breaks and indentation.

Writing as follows can also run well:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js">
    </script>
    <script>
        $(document).ready(function()
        {
            $("button").click(function(){
                $("#p1").css("color","red")
                        .slideUp(2000)
                        .slideDown(2000);
            });
        });
    </script>
</head>
<body>
<p id="p1">php中文网!!</p>
<button>点我</button>
</body>
</html>

Run it and try it

Tips: jQuery will throw away extra spaces and treat them as one line long code to execute the above line of code.



Continuing Learning
||
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"> </script> <script> $(document).ready(function() { $("button").click(function(){ $("#p1").css("color","red") .slideUp(2000) .slideDown(2000); }); }); </script> </head> <body> <p id="p1">php中文网(php.cn)</p> <button>点我</button> </body> </html>
submitReset Code