The clone() method makes a copy of selected elements, including child nodes, text, and attributes.
Try it Yourself - Copy paste code in Online HTML Editor to see the result
Syntax
$(selector).clone(true|false)
- true - Specifies that event handlers also should be copied
- false - Default. Specifies that event handlers should not be copied
Example 1
Clones all b elements (and selects the clones) and prepends them to all paragraphs.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>clone demo</title>
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
</head>
<body>
<b>Hello</b>
<p>, how are you?</p>
<script>
$("b").clone().prependTo("p");
</script>
</body>
</html>
Example 2
Clone all elements and insert them at the end of the element:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("button").click(function() {
$("p").clone().appendTo("body");
});
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Clone all p elements, and append them to the body element</button>
</body>
</html>
Comments
Post a Comment