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: /
Thanks in advance.
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/dmperkins74/zvdekh8p/
Thanks in advance.
Share Improve this question asked Jan 22, 2015 at 12:24 dmperkins74dmperkins74 1675 silver badges12 bronze badges3 Answers
Reset to default 4You 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 cloning
document.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):
function appendNCopies(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);
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
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 cloning
document.body.appendChild(divClone);
}