clone method in jQuery with example


1. clone() method creates copy of the set of matched elements.
2. clone() method performs deep copy, it not only matches the matched element, but also their descendant elements and text nodes.
3. clone() method is a convenient way to duplicate elements on the page.


Example 1 :



        <html>
        <head>
        <title>clone</title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> 
        </script>
        <script type="text/javascript">
            $(document).ready(function () {
                $("#myButton").click(function () {
                    $("#targetP").clone().appendTo($('#targetDiv'));
                });
            });
        </script>
        </head>
        <body>
        <p id="targetP">Jquery is amazing.</p>
        <div id="targetDiv"></div>
        <input type="button" id="myButton" value="Clone"/>
        </body>
        </html>
    

Demo :



In the above example, we have demonstrated how to use clone() method to duplicate elements on the page. we have a paragraph element on the page, on clicking "Clone" button we are selecting this paragraph element and using clone() method we are creating its duplicate and appending to div element.

Example 2 :



        <html>
        <head>
        <title>clone</title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> 
        </script>
        <script type="text/javascript">
            $(document).ready(function () {
                $("#myButton").click(function () {
                    $("#cloneDiv").clone().appendTo($('#targetDiv'));
                });
            });
        </script>
        </head>
        <body>
        <div id="cloneDiv">
        This is div element.
        <p>This is p element inside div element.</p>
        <p>clone() performs deep copy, that is not only copies the matched elements but also their 
        descendants and text nodes.</p>
        </div>
        <div id="targetDiv">
        </div>
        <input type="button" id="myButton" value="Clone"/>
        <input type="button" id="reset" value="Reset" onclick="location.reload()" />
        </body>
        </html>
    
Demo :




In the above example, we have created a div with id as "clonediv". On button click, we are selecting cloneDiv and using clone() method its copy is created and appended to div with id "targetDiv". This examples shows that clone() method performs deep copy, that is copies all descendants and text nodes.


0 comments:

Post a Comment