Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

186
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda