如何在 JavaScript 中复制 div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19482076/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to duplicate a div in JavaScript
提问by utopy
I was wondering how I can duplicate a DIV
element a few times through JavaScript without duplicating the DIV in my html code?
我想知道如何DIV
通过 JavaScript 多次复制一个元素而不在我的 html 代码中复制 DIV?
回答by Benjamin Gruenbaum
Let's assume the you selected the div doing something like:
让我们假设您选择了 div 执行以下操作:
var myDiv = document.getElementById("myDivId");
The DOM API contains a cloneNode
method which you can use
DOM API 包含一个cloneNode
您可以使用的方法
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