jQuery clone() Method

jQuery | clone() Method: Learn about the jQuery clone() Method with its usages, syntax, and examples.
Submitted by Pratishtha Saxena, on October 15, 2022

clone() Method

First of all, let's consider a situation – where you need to have multiple exactly created elements on the page. It should have the same contents, same styling, save working, etc. Basically, you need to make multiple copies of already created content on the same web page. Therefore, in these types of situations when you need to copy some elements, the clone() method is useful.

This method helps to create a copy of the selected element and return it to the web page. It copies everything related to it – like its styles, text, child nodes, other attributes, etc. Therefore, this method saves a lot of time by making a copy of the required element.

clone() Method Syntax

$('selector').clone(true|false);

The clone() takes in true/false as its parameters. It specifies that the event handler should also be copied or not of the selected element. If yes, then pass 'true', otherwise 'false'. By default, when nothing is specified, it takes false. Let's see the following example which shows the implementation of the clone() method. It appends the copy of the image to the body of the document when the button is clicked. This way you can append the cloned element wherever you need to.

jQuery clone() Method Example

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <title>Document</title>
  </head>
  <body>
    <h2>jQuery - Clone</h2>
    <p>Click the button to make a copy of the selected content.</p>
    <button>Clone</button>
    <hr>
    <img style="height: 200px;" id="myImg" src="https://media.istockphoto.com/photos/mountain-landscape-picture-id517188688?k=20&m=517188688&s=612x612&w=0&h=i38qBm2P-6V4vZVEaMy_TaTEaoCMkYhvLCysE7yJQ5Q=">
  </body>
  
  <script type="text/javascript">
    $(document).ready(function(){
        $("button").click(function(){
            $('img').clone().appendTo('body');
        });
    });
  </script>
</html>

Output:

Example 1: jQuery clone() Method



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.