Open In App

jQuery clone() Method

Improve
Improve
Like Article
Like
Save
Share
Report

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

Syntax:

$(selector).clone(true|false)

Parameters: This method accepts an optional parameter that could be either true or false specifying whether the event handler should be copied or not. 

Return Value: It returns the cloned elements for the selected element.

Example 1: In this example, the clone() method does not contain any parameters. 

HTML




<!DOCTYPE html>
<html>
 
<head>
    <script src=
    </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>


Output:

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

HTML




<!DOCTYPE html>
<html>
 
<head>
    <script src=
    </script>
 
    <!-- Here clone method is called with the
          true passed value -->
    <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, the code event handler animation will work when you click on the “GeeksforGeeks” and this will also reflect on the cloned elements. 

Output: 



Last Updated : 07 Jul, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads