jQuery Clone()

The jQuery clone() method creates a copy of selected elements, including their attributes and content. This is useful for duplicating elements in the DOM dynamically.

Key Topics

Basic Usage of clone()

The clone() method creates a shallow copy of the selected element.

// Clone an element
var clonedElement = $("#element").clone();
$("#container").append(clonedElement);

Explanation: This code clones the element with the ID element and appends the clone to the element with the ID container.

Deep Cloning

By default, clone() does not copy event handlers and data. To clone these as well, pass true as an argument.

// Deep clone an element
var deepClonedElement = $("#element").clone(true);
$("#container").append(deepClonedElement);

Explanation: Passing true to clone() copies event handlers and data associated with the original element.

Example: Using clone()


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery Clone Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <div id="original" class="box">Original Box</div>
    <div id="container"></div>
    <button id="cloneButton">Clone Box</button>

    <script>
        $(document).ready(function() {
            $("#cloneButton").click(function() {
                var clone = $("#original").clone();
                $("#container").append(clone);
            });
        });
    </script>
</body>
</html>
                    

Explanation: This example demonstrates how to clone an element and append it to another element dynamically when a button is clicked.

Key Takeaways

  • Shallow Cloning: Use clone() to duplicate elements without event handlers or data.
  • Deep Cloning: Pass true to clone() to include event handlers and data in the cloned element.
  • Dynamic Duplication: Ideal for creating copies of UI components dynamically.