最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Clone a Div Multiple Times - Stack Overflow

programmeradmin9浏览0评论

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 badges
Add a ment  | 

3 Answers 3

Reset to default 4

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 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);
 }
发布评论

评论列表(0)

  1. 暂无评论