Google News
logo
jQuery Method Chaining
The jQuery chaining statements one at a time (one after the other), this is a called chaining technique. That allows us to run multiple jQuery commands in a single line of code.  This way, browsers do not have to find the same element(s) more than once.

To chain an action, you simply append the action to the previous action. The following example chains together the css(), slideUp(), and slideDown() methods. The "p1" element first changes to red, then it slides up, and then it slides down  :
<!DOCTYPE html>
<html>
<head>
<title>jQuery Method Chaining</title>
 
<script src="js/jquery-3.2.1.min.js"></script>  
<script type="text/javascript">
$(document).ready(function(){
    $("button").click(function(){
        $("#p1").css("color", "#FFF").slideUp(2000).slideDown(2000);
    });
});
</script>
<style type="text/css">
.btn{ padding:6px 15px;}
     p{ background:#0099da; font-size: 24px;padding:20px; color:#FFF; text-align:center;}
</style>
</head>
 
<body>
 
    <button type="button" class="btn">Click Here!</button>
    <p id="p1">This is a sample "jQuery chaining method".</p>   
    
</body>
</html> 
Output :

The jQuery chaining, is the line of code could become quite long. However, jQuery is not very strict on the syntax; you can format it like you want, including line breaks and indentations.

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

<!DOCTYPE html>
<html>
<head>
<title>jQuery Method Chaining - Log line of Code</title>
 
<script src="js/jquery-3.2.1.min.js"></script>  
<script type="text/javascript">
$(document).ready(function(){
    $("button").click(function(){
        $("#p1").css("color", "red")
            .slideUp(2000)
            .slideDown(2000);
    });
});
</script>
<style type="text/css">
.btn{ padding:6px 15px;}
     p{ background:#0099da; font-size: 24px;padding:20px; color:#FFF; text-align:center;}
</style>
</head>
 
<body>
 
    <button type="button" class="btn">Click Here!</button>
    <p id="p1">This is a sample "jQuery chaining method".</p>   
    
</body>
</html> 
Output :