The jQuery clone() method copies the selected elements, including everything associated with them such as event handlers, child elements, text, attributes, values etc. It then inserts the copy of the selected elements in the html page body.
Syntax of jQuery clone() method
$(selector).clone(true|false)
$(selector): It selects the elements that are copied by the clone() method. Read more at jQuery Selectors.
true|false: The default value ‘false’ specifies that just copy the elements and ignore the event handlers. The ‘true’ value specifies that copy the event handlers along with the selected elements. By default the value is considered ‘false’ in clone() method.
jQuery clone() Method Example
In the following example, we have a unordered list of fruit names. These fruit names are the list items. We have added an event handler for the first list item, this event occurs when user clicks on the first list item. Once this event triggers, it increases the font size of the first list item by 10px.
We have made a copy of the first list item using clone() method. Since we have passed the ‘true’ value in the clone() method, it copied the event handler associated with the first list item along with the it and then appended it to the body as shown in the output screen.
We can also verify whether the event handler is correctly copied along with element by clicking the copied element. Upon clicking, it increased the font size by 10 px which is shown in the third screenshot below.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("body").append($("li:first").clone(true));
});
$("li").click(function(){
$(this).animate({fontSize: "+=10px"});
});
});
</script>
</head>
<body>
<p>To copy the first list item (including event handlers) and
append at the end of page body, </p><button>click here!</button>
<p>click the list item to increase font size</p>
<ul>
<li>Apple</li>
<li>Orange</li>
<li>Grapes</li>
<li>Mango</li>
<li>Banana</li>
</ul>
</body>
</html>
Output:
Before the button click:
After the button click: The first list item is copied and appended in the body.
After clicking the appended list item: The font size of the copied list item increased, which confirms that the event handler is also copied along with it.
Leave a Reply