Open In App

What is chaining in jQuery ?

Last Updated : 14 Jul, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

In jQuery, chaining allows us to perform multiple operations on an element in a single statement.

Most of the jQuery function returns a jQuery object and due to this when the first method completes its execution, it returns an obj now the second method will be called on this object.

Example 1: With the help of chaining, we develop our code concisely.  Chaining also makes our script faster because now the browser doesn’t have to find the same element to perform operations on them. Every method of the ‘gfg’ object is returning an object.

First, the geek() method is called, and then the write() method is called, then the destroy() method is called.

HTML




<!DOCTYPE html>
<head>
  <script src=
  </script>
</head>
  
<body>
    <script>
        let gfg = {
            geek: function(){
                alert('called geek method');
                return gfg;
            },
            write: function(){
                alert('called write method');
                return gfg;
            },
            destroy: function(){
                alert('called destroy method');
                return gfg;
            }
        }
  
        gfg.geek().write().destroy();
    </script>
</body>
  
</html>



 

Output:

Example 2: The following code demonstrates the chaining of fadeOut() and fadeIn() method. Every time you click on the button, the text will first fade out and then fade in.

HTML




<!DOCTYPE html>
<head>
    <!-- jQuery library -->
    <script src="https://code.jquery.com/jquery-git.js"></script>
</head>
  
<body>
    <p id="first">GeeksForGeeks</p>
  
    <button>click me</button>
    <script>
        $(document).ready(function(){
            $('button').click(function(){
                $('#first').fadeOut(100).fadeIn(100);
            })
        })
    </script>
</body>
  
</html>


Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads