I was wondering how I can duplicate a DIV
element a few times through JavaScript without duplicating the DIV in my html code?
You call the cloneNode() method on the element you want to copy. If you want to also copy elements nested inside it, pass in true as an argument. // Get the element var elem = document. querySelector('#elem1'); // Create a copy of it var clone = elem.
First, select the div element which need to be copy into another div element. Select the target element where div element is copied. Use the appendTo() method to copy the element as its child.
Right click on a node and select Copy. You can paste in your code editor, or for prototyping, you can paste the DOM node elsewhere in the DOM tree. The pasted node is inserted as a child of the currently selected node.
From the HTML provided, start copying the HTML with the first table tag so you include the necessary content. Copy all the way through to the end table tag. Use the Control + C shortcut to copy or right click on your selected text and click Copy. Create a new page in your Site.
Let's assume the you selected the div doing something like:
var myDiv = document.getElementById("myDivId");
The DOM API contains a cloneNode
method which you can use
var divClone = myDiv.cloneNode(true); // the true is for deep cloning
Now you can add it to the document
document.body.appendChild(divClone);
Here is a short self contained code example illustrating this
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With