Cover Image for jQuery clone() method
78 views

jQuery clone() method

The jQuery clone() method is used to create a deep copy of the selected elements, including all of their child elements and text nodes. It allows you to duplicate elements in the DOM, creating independent copies that can be inserted at different locations or manipulated separately.

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

$(selector).clone([withDataAndEvents[, deepWithDataAndEvents]]);
  • selector: It is a string that specifies the elements to be selected.
  • withDataAndEvents (optional): It is a boolean value that indicates whether to include event handlers and data associated with the selected elements. By default, it is set to false, meaning event handlers and data are not copied. If you want to include event handlers and data, set it to true.
  • deepWithDataAndEvents (optional): It is a boolean value that indicates whether to recursively clone all child elements and their data and events. By default, it is set to false, meaning only the selected element is cloned. If you want to clone all child elements as well, set it to true.

Here’s an example of how you can use the clone() method:

HTML:

<div id="original">
  <p>This is a paragraph.</p>
</div>

JavaScript:

// Clone the original div element
var clonedElement = $('#original').clone();

// Modify the text inside the cloned element
clonedElement.find('p').text('This is the cloned paragraph.');

// Insert the cloned element after the original element
clonedElement.insertAfter('#original');

After executing the above JavaScript code, a new copy of the original div element will be created with the modified text, and it will be inserted after the original element:

Resulting HTML:

<div id="original">
  <p>This is a paragraph.</p>
</div>

<div id="original">
  <p>This is the cloned paragraph.</p>
</div>

In the example, the clone() method is used to create a copy of the original div element, including its child p element. The text() method is then used to modify the text inside the cloned p element. Finally, the insertAfter() method is used to insert the cloned element after the original element.

The clone() method is useful when you want to duplicate elements in the DOM and manipulate them independently. It allows you to reuse or modify existing structures easily, and it can be used to implement features such as adding or removing multiple elements dynamically.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS