We can use the jQuery clone() method to copy an existing HTML element and add a copy of it to our HTML.
$("#div1").clone();
The jQuery clone() method would copy the div #div1 and any elements it contains.
If you are using WordPress, don’t forget to change the $ to jQuery as below:
jQuery("#div1").clone();
Let’s take a look at an example.
Let’s say we have the following HTML:
This is some text.
Clone and add text above
Let’s say we want to copy the paragraph above and add it to the div. We can do this easily with the jQuery clone() method. We can also use the appendTo() method to then add the cloned paragraph to the div.
Here is the JavaScript code:
$("#click-me1").click(function(){
//We only want to clone the first p, so we use :first
var clonedP = $(".p1:first").clone();
clonedP.appendTo("#div1");
});
Here is the final code and output for this example:
Code Output:
This is some text.
Full Code:
This is some text.
Clone and add text above
Let’s take a look at another example below.
Using the jQuery clone() Method to Create a Bunch of Divs
In this simple example, we will have a div that will be a box with a greenish background. We will provide a button for the user be able to clone this div, and add its clone right next to it. Here is the HTML setup:
Clone box
In our function, we will clone the div, and then change its background color using the css() method.
We will finally add the new div using the appendTo() method like we did in the example above.
$("#click-me2").click(function(){
var clonedP = $(".box:first").clone();
//Create a random color
var randomColor = "#" + (Math.floor(Math.random()*16777215).toString(16));
//Give the new box a random background color
clonedP.css("background",randomColor);
clonedP.appendTo("#div2");
});
The final code and output for this example of using the jQuery clone() method to create a bunch of divs is below:
Code Output:
Full Code:
Clone box
Hopefully this article has been useful for you to understand how to use the jQuery clone() method to make a copy of an element.