js-复制所有子节点 [英] js - duplicate all child nodes
本文介绍了js-复制所有子节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想复制容器中的所有子节点,然后将它们插入同一容器中。
I want to duplicate all child nodes in a container, and insert them in the same container.
例如,我有:
<div id="container">
<div class="square red"></div>
<div class="square green"></div>
</div>
运行此JS之后:
function duplicateChildNodes (parentId){
var parent = document.getElementById(parentId);
NodeList.prototype.forEach = Array.prototype.forEach;
var children = parent.childNodes;
children.forEach(function(item){
parent.appendChild(item);
});
};
duplicateChildNodes("container");
我应该有:
<div id="container">
<div class="square red"></div>
<div class="square green"></div>
<div class="square red"></div>
<div class="square green"></div>
</div>
由于某种原因,它不起作用。我该如何解决?
一支笔: https://codepen.io/ t411tocreate / pen / gXqYWj
For some reason, it doesen't work. How do I solve it ?
A pen: https://codepen.io/t411tocreate/pen/gXqYWj
推荐答案
dom元素仅存在于一个位置,因此在追加后将其移至新位置(在您的情况下,它已删除并附加到同一位置)
that dom element only exists in one place so after append it is moved to a new place (in your case it is removed and appended to the same place)
您首先需要克隆节点。例如: var cln = itm.cloneNode(true);
You need clone node first. ex: var cln = itm.cloneNode(true);
请检查以下更新的示例:
check the updated example below:
function duplicateChildNodes (parentId){
var parent = document.getElementById(parentId);
NodeList.prototype.forEach = Array.prototype.forEach;
var children = parent.childNodes;
children.forEach(function(item){
var cln = item.cloneNode(true);
parent.appendChild(cln);
});
};
duplicateChildNodes("container");
#container{
border: 1px solid #ccc;
padding: 2px;
}
.square{
width: 100px;
height: 100px;
display: block;
margin: 2px;
}
.red{
background: red;
}
.green{
background: green;
}
<div id="container">
<div class="square red"></div>
<div class="square green"></div>
</div>
这篇关于js-复制所有子节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文