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

180
Visualizações
element disappears when appended to other element

document.querySelectorAll('.image').forEach(el => {
 el.querySelector('span').addEventListener('click', (e) => {
   const clickedElement = e.target;
   document.querySelector('.append').append(clickedElement);
 });
});
.image {
 background: red;
 cursor: pointer;
}

.append {
 margin-top: 20px;
 background: yellow;
}
<div class="image">
  <span>image1</span>
</div>
<div class="image">
 <span>image2</span>
</div>

<div class="append"></div>

So I am trying to figure it out why when I click image1 or image2 text in red background it appends to yellow background but it disappears from red background? How to stop it from disappearing from red background?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You need to clone the element to make a copy using Node.cloneNode():

const clickedElement = e.target.cloneNode(true);

document.querySelectorAll('.image').forEach(el => {
 el.addEventListener('click', (e) => {
   const clickedElement = e.target.cloneNode(true);
   document.querySelector('.append').append(clickedElement);
 });
});
.image {
 background: red;
 cursor: pointer;
}

.append {
 margin-top: 20px;
 background: yellow;
}
<div class="image">
  <span>image1</span>
</div>
<div class="image">
 <span>image2</span>
</div>

<div class="append"></div>

about 4 years ago · Juan Pablo Isaza Relatório

0

.append() is moving the node itself-- .cloneNode(true) (passed true to clone the subtree as well) will create a copy you can append while leaving the original in place in the DOM:

document.querySelectorAll('.image').forEach(el => {
 el.addEventListener('click', (e) => {
   const clickedElement = e.target;
   const clonedElement = clickedElement.cloneNode(true);
   document.querySelector('.append').append(clonedElement);
 });
});
.image {
 background: red;
 cursor: pointer;
}

.append {
 margin-top: 20px;
 background: yellow;
}
<div class="image">
  <span>image1</span>
</div>
<div class="image">
 <span>image2</span>
</div>

<div class="append"></div>

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