Search code examples
javascriptclone

Clone a Div Multiple Times


please be gentle, I'm just learning. I'm trying to clone a div multiple times. I can get it to do it once, but not several times. I'd like to do it w/out JQuery (trying to understand basic Javascript first). Below is a sample. What am I doing wrong?

var myDiv = document.getElementById("test");
var divClone = myDiv.cloneNode(true); // the true is for deep cloning
document.body.appendChild(divClone);
document.body.appendChild(divClone);
document.body.appendChild(divClone);

Here it is on jsfiddle: http://jsfiddle.net/dmperkins74/zvdekh8p/

Thanks in advance.


Solution

  • You need to clone it each time.

    var myDiv = document.getElementById("test");
    
    document.body.appendChild(myDiv.cloneNode(true));
    document.body.appendChild(myDiv.cloneNode(true));
    document.body.appendChild(myDiv.cloneNode(true));
    

    fiddle