Skip to content Skip to sidebar Skip to footer

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 understa

Solution 1:

You need to clone it before each insertion. I updated your fiddle:

var myDiv = document.getElementById("test");

var divClone = myDiv.cloneNode(true); // the true is for deep cloningdocument.body.appendChild(divClone);
divClone = myDiv.cloneNode(true);
document.body.appendChild(divClone);
divClone = myDiv.cloneNode(true);
document.body.appendChild(divClone);

This happens because each node is exactly one node, and can exist only in one place. This is why you copy it before appending it again.

You could wrap the functionality in a function to use it several times (theres a fiddle for this, too):

functionappendNCopies(n, original, appendTo) {
    for(var i = 0; i < n; i++) {
        var clone = original.cloneNode(true);
        appendTo.appendChild(clone);
    }
}

var myDiv = document.getElementById("test");
appendNCopies(3, myDiv, document.body);

Solution 2:

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

Solution 3:

you are creating cloneNode only once thats why this is happening. use this code :

var myDiv = document.getElementById("test");

var  divClone;
for(var i=0;i<10;i++)
 {
   divClone = myDiv.cloneNode(true); // the true is for deep cloningdocument.body.appendChild(divClone);
 }

Post a Comment for "Clone A Div Multiple Times"