Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

jQuery | clone() with Examples

  • Difficulty Level : Hard
  • Last Updated : 13 Feb, 2019

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.

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!




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




My Personal Notes arrow_drop_up
Recommended Articles
Page :