如何在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 15:44:10  来源:igfitidea点击:

How to duplicate a div in JavaScript

javascripthtmlcss

提问by utopy

I was wondering how I can duplicate a DIVelement 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 cloneNodemethod 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

这是一个简短的自包含代码示例,说明了这一点