Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to duplicate a div in JavaScript

I was wondering how I can duplicate a DIV element a few times through JavaScript without duplicating the DIV in my html code?

like image 608
utopy Avatar asked Oct 20 '13 19:10

utopy


People also ask

How do I clone a div using Javascript?

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.

How do you replicate a div?

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.

How do I copy a DOM?

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.

How do you duplicate in HTML?

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.


1 Answers

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

like image 67
Benjamin Gruenbaum Avatar answered Oct 08 '22 05:10

Benjamin Gruenbaum