• jQuery Video Tutorials

jQuery clone() Method



The clone() method in jQuery is used to create a deep copy of elements selected by a jQuery selector. It duplicates the selected elements, including all descendant elements and their attributes.

This method allows you to replicate elements in the DOM structure without losing event handlers or data associated with them.

Syntax

Following is the syntax of clone() method in jQuery −

$(selector).clone(true|false)

Parameters

This method accepts the following parameters −

  • true: It specifies that the event handlers should also be copied.
  • false: It specifies that the event handlers should not be copied. This is the default value.

Example 1

In the following example, we are cloning the <span> element and inserting it at the end of the <p> element −

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("span").clone().appendTo("p");
    });
});
</script>
</head>
<body>
<span>This is a span element...</span>
<p>Paragraph element.</p>
<button>Clone Div</button>
</body>
</html>

When we click the button, the <span> element will be inserted at the end of the <p> element

Example 2

In the example below, we are using the clone() method to copy an element, including event handlers −

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
  //Original Button
    $(".originalButton").click(function(){
        alert("Original Button Clicked!");
    });
  //Clone Button
    $(".cloneButton").click(function(){
        $(".originalButton").clone(true).appendTo("div");
    });
});
</script>
</head>
<body>
<div>
    <button class="originalButton">Original Button</button>
</div>
<button class="cloneButton">Clone Button</button>
</body>
</html>

The original button element has a click event handler attached to it. When you click the "Original Button", an alert will be displaying.

Clicking the "Clone Button" clones the original button along with its click event handler and appends it to the container div. You can then click the cloned button, and it will trigger the same event handler, showing the alert message.

jquery_ref_html.htm
Advertisements