Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

210
Views
How copying elements without deleting originals?

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!

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]);
}
<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>

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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);
about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!