I want to duplicate all child nodes in a container, and insert them in the same container.
For example, I have:
<div id="container">
<div class="square red"></div>
<div class="square green"></div>
</div>
And after running this 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");
I should have:
<div id="container">
<div class="square red"></div>
<div class="square green"></div>
<div class="square red"></div>
<div class="square green"></div>
</div>
For some reason, it doesen't work. How do I solve it ?
A pen:
I want to duplicate all child nodes in a container, and insert them in the same container.
For example, I have:
<div id="container">
<div class="square red"></div>
<div class="square green"></div>
</div>
And after running this 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");
I should have:
<div id="container">
<div class="square red"></div>
<div class="square green"></div>
<div class="square red"></div>
<div class="square green"></div>
</div>
For some reason, it doesen't work. How do I solve it ?
A pen: https://codepen.io/t411tocreate/pen/gXqYWj
-
that dom element only exists in one place so after append it is moved to a new place, you need clone node first. ex:
var cln = itm.cloneNode(true);
– Dalin Huang Commented Dec 1, 2017 at 21:30
1 Answer
Reset to default 13that 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)
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>