Skip to content
Related Articles

Related Articles

jQuery | clone() with Examples
  • Last Updated : 13 Feb, 2019
GeeksforGeeks - Summer Carnival Banner

The clone() is an inbuilt method in jQuery which is used to make a copy of selected elements including its child nodes, text and attributes.
Syntax:

$(selector).clone(true|false)

Parameter: It accepts an optional parameter which could be either true or false specifies that event handler should be copied or not.
Return Value : It returns the cloned elements for the selected element.

jQuery code to show the working of this method:

Code #1:
In the below code, no true or false is passed to the change method.




<html>
  
<head>
               jquery/3.3.1/jquery.min.js"></script>
                 
    <!--In this example no parameter is passing to the 
        clone method-->
    <script>
        $(document).ready(function() {
            $("button").click(function() {
                $("p").clone().appendTo("body");
            });
        });
    </script>
</head>
  
<body>
    <p>Welcome to</p>
    <p>GeeksforGeeks !!!</p>
    <!--click on this method and see the clone element-->
    <button>Click Me!</button>
</body>
  
</html>

Before clicking the “Click Me” button-

After clicking the “Click Me” button-

Code #2:
In the below code, true is passed to the clone method.






<html>
  
<head>
                jquery/3.3.1/jquery.min.js"></script>
    <!--here clone method is called with the true value passing-->
    <script>
        $(document).ready(function() {
            $("button").click(function() {
                $("body").append($("p:first").clone(true));
            });
            $("p").click(function() {
                $(this).animate({
                    fontSize: "+=1px"
                });
            });
        });
    </script>
</head>
  
<body>
    <p>GeeksforGeeks !</p>
    <p>Hello Writer !</p>
    <!--click on this method and see the clone element-->
    <button>Click Me!</button>
</body>
  
</html>

In this example code event handler animate will work when you click on the “GeeksforGeeks” and this will also reflect on the cloned elements.
Output:
Before clicking the “Click Me” button-

After clicking the “Click Me” button-

full-stack-img

My Personal Notes arrow_drop_up
Recommended Articles
Page :