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

190
Views
JS Cloning html element results in losing initial element

I am trying to pick out from a list of splide objects both the last element of the list (elementA ) and a specific element (with index -1, elementB ). I want to exchange a sub-element of elementB with a sub-element (same class name) of elementA . Unfortunately this doesn't work, because every time the subelement of elementA is removed and I can't find out why. It is correctly inserted into elementB , but is no longer in the DOM of elementA.

Below is the code:

const elementA = splide.Components.Slides.getAt(lastIndex);
const elementB = splide.Components.Slides.filter(slide => slide.index === -1);

const elementAContent= elementA[0].slide.querySelector('.element-container');
const elementBContent= elementB[0].slide.querySelector('.element-container');

const elementAToBeCloned = elementAContent.querySelector('.clone-element');

elementBContent.removeChild(elementBContent.firstElementChild);

elementBContent.insertBefore(elementAToBeCloned, elementBContent.firstElementChild); 
//doing so results in elementAToBeCloned to be lost within elementAContent

I also tried to do something with .cloneNode(true) or with replaceChild but unfortunately the behaviour is always the same.

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

0

You didn't actually clone anything - you just performed an insertBefore command on an existing element, so that element got moved. You need to call .cloneNode() to clone elements and you need to do that before you place the cloned node at a location in the DOM.

const elementToClone = document.querySelector("div");
document.querySelector("button").addEventListener("click", function(evt){
  // Insert a newly cloned node at the end of the <body>
  document.body.insertBefore(elementToClone.cloneNode(true),document.body.lastChild);
});
<div>Foo Bar</div>
<button type="button">Clone</button>

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!