jquery
  1. jquery-clone

jQuery clone()

The jQuery clone() method is used to create a copy of the selected element(s), including all of its child elements and their properties.

Syntax

The basic syntax for using the clone() method is as follows:

$(element).clone(withDataAndEvents)
  • element: The element(s) you want to clone.
  • withDataAndEvents: A boolean value that indicates whether to include the element's data and events in the clone. This is an optional parameter and defaults to false.

Use

The clone() method is useful when you want to create a copy of an element with all of its child elements and properties intact. This can be especially useful when working with dynamic web applications, such as e-commerce or web-based forms, where you need to create or duplicate elements on the fly.

Example

Here is an example of using the clone() method to create a copy of a form field:

<!DOCTYPE html>
<html>
<head>
    <title>jQuery clone() Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <form>
        <input type="text" name="username" id="username"/><br><br>
        <input type="text" name="email" id="email"/><br><br>
    </form>
    <button id="cloneBtn">Clone Field</button>
    <script>
        $(document).ready(function(){
            $("#cloneBtn").click(function(){
                var clonedField = $("#username").clone();
                $(clonedField).attr("id","newUsername");
                $(clonedField).insertAfter("#username");
            });
        });
    </script>
</body>
</html>
Try Playground

In this example, we have a form with two input fields, "username" and "email". We also have a button that, when clicked, clones the "username" field and inserts it after the original "username" field. We're also setting a new ID for the cloned field using jQuery's attr() method.

Summary

The clone() method in jQuery is a quick and easy way to create copies of elements with all of their child elements and properties. It can be used in a variety of applications, such as creating dynamic web-based forms or duplicating elements on the fly. With the ability to include or exclude data and events from the clone, the clone() method offers a flexible solution to common web development tasks.

Published on: