jQuery | clone() with Examples

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

<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>

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

<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>

chevron_right


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-



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.