Home > front end >  How copying elements without deleting originals?
How copying elements without deleting originals?

Time:10-15

I have a loop to duplicate an array, and another to add copy in another div. Both loop work good but original element are deleted, someone can explain me why? And how can i fixe it? Thank you!

<div class="parent_element" style="background-color: red;">
    <div class="element">text</div>
    <div class="element">text</div>
    <div class="element">text</div>
</div>
<div class="parent_copy" style="background-color: green;"></div>

var mesElements = document.querySelectorAll('.element');
var catchCopy = document.querySelector('.parent_copy');

var mesElementsCopie = []
for(var j = 0; j < mesElements.length;   j){
    mesElementsCopie[j] = mesElements[j];
}
for(var k = 0; k < mesElements.length;   k){
    catchCopy.appendChild(mesElementsCopie[k]);
}

CodePudding user response:

On this line, you do not copy the node, but rather you create two references to the same DOM node:

mesElementsCopie[j] = mesElements[j];

You should use the cloneNode() method:

mesElementsCopie[j] = mesElements[j].cloneNode(true);

CodePudding user response:

Here's the fixed code:

var mesElements = document.querySelectorAll('.element');
var catchCopy = document.querySelector('.parent_copy');

var mesElementsCopie = []
for(var j = 0; j < mesElements.length;   j){
    mesElementsCopie[j] = mesElements[j].cloneNode(true);
}
for(var k = 0; k < mesElements.length;   k){
    catchCopy.appendChild(mesElementsCopie[k]);
}
<div class="parent_element" style="background-color: red;">
    <div class="element">text</div>
    <div class="element">text</div>
    <div class="element">text</div>
</div>
<div class="parent_copy" style="background-color: green;"></div>

You were adding the same elements you had grabbed from the parent element, so it was just moving them to the parent copy. Use .cloneNode(true) to make sure you're not using the same element.

  • Related