utopy
utopy

Reputation: 187

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?

Upvotes: 15

Views: 21357

Answers (1)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276306

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

Upvotes: 42

Related Questions