jQuery clone() Method (original) (raw)
Last Updated : 07 Jul, 2023
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 `
<!--In this example no parameter is passing
to the clone method-->
<script>
$(document).ready(function () {
$("button").click(function () {
$("p").clone().appendTo("body");
});
});
</script>
Welcome to
GeeksforGeeks !!!
<!-- Click on this method and see
the clone element-->
<button>Click Me!</button>
`
**Output:
**Example 2: In the below code, true is passed to the clone method.
HTML `
<!-- Here clone method is called with the
true passed value -->
<script>
$(document).ready(function () {
$("button").click(function () {
<span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mo stretchy="false">(</mo><mi mathvariant="normal">"</mi><mi>b</mi><mi>o</mi><mi>d</mi><mi>y</mi><mi mathvariant="normal">"</mi><mo stretchy="false">)</mo><mi mathvariant="normal">.</mi><mi>a</mi><mi>p</mi><mi>p</mi><mi>e</mi><mi>n</mi><mi>d</mi><mo stretchy="false">(</mo></mrow><annotation encoding="application/x-tex">("body").append(</annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mopen">(</span><span class="mord">"</span><span class="mord mathnormal">b</span><span class="mord mathnormal">o</span><span class="mord mathnormal">d</span><span class="mord mathnormal" style="margin-right:0.03588em;">y</span><span class="mord">"</span><span class="mclose">)</span><span class="mord">.</span><span class="mord mathnormal">a</span><span class="mord mathnormal">pp</span><span class="mord mathnormal">e</span><span class="mord mathnormal">n</span><span class="mord mathnormal">d</span><span class="mopen">(</span></span></span></span>("p:first").clone(true));
});
$("p").click(function () {
$(this).animate({
fontSize: "+=1px"
});
});
});
</script>
GeeksforGeeks !
Hello Writer !
<!-- Click on this method and see
the clone element -->
<button>Click Me!</button>
`
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: