Open In App

How to use Method Chaining in jQuery ?

Improve
Improve
Like Article
Like
Save
Share
Report

jQuery is an open-source JavaScript library that simplifies the interactions between an HTML/CSS document, or more precisely the Document Object Model (DOM), and JavaScript. Elaborating the terms simplifies HTML document traversing, manipulation, browser event handling, DOM animations, AJAX interactions, and cross-browser JavaScript development.

What is the Method Chaining?

jQuery provides another robust feature called method chaining that allows us to perform multiple actions on the same set of elements, all within a single line of code.

 

How does it work?

We instantiate a new jQuery object, which allows us to manipulate the selected element. The chaining method returns the jQuery object again, allowing us to use another method called directly on the return value, which is the CSS() method.

Syntax:

$(‘selector’).method1().method2().method3()

Example 1:  We are adding two methods one is animation in width and another is animation in font size.

$("p").animate({width: "100%"}).animate({fontSize: "46px"});

HTML




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="utf-8">
    <script src=
    </script>
    <style>
        p {
            width: 200px;
            padding: 40px 0;
            font: bold 24px sans-serif;
            text-align: center;
            background: #aaccaa;
            border: 1px solid #63a063;
            box-sizing: border-box;
        }
    </style>
</head>
  
<body>
    <h1 style="color:green">GeeksforGeeks</h1>
    <h3><b>Chaining</b></h3>
  
    <p>GeeksforGeeks</p>
    <button type="button" class="start">
        Start Chaining</button>
    <script>
        $(document).ready(function () {
            $(".start").click(function () {
                $("p").animate({ width: "100%" })
                    .animate({ fontSize: "46px" });
            });
        });  
    </script>
</body>
  
</html>


Output:

 

Example 2: In the following code, we are hiding the button using the concept of chaining in jQuery.

HTML




<!DOCTYPE html>
<html>
  
<head>
  
    <script src=
    </script>
</head>
  
<body>
    <h1 style="color:green">GeeksforGeeks</h1>
    <p id='gfg'>Button!!! Hide me</p>
  
    <button>Click me</button>
  
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                $("#gfg").css("color", "green")
                  .slideUp(1909);
            });
        });
    </script>
</body>
  
</html>


Output:

 



Last Updated : 28 Sep, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads