Home > Net >  JS Cloning html element results in losing initial element
JS Cloning html element results in losing initial element

Time:05-04

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.

CodePudding user response:

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>

  • Related