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

299
Visualizações
After first append javascript is not adding a cloned item for the second time

In my application I am adding cloned elements:

        document.getElementById("add").addEventListener("click", function(){
            let theblock = document.getElementById("theblock").cloneNode(true);
            let newer = theblock;
            newer.removeAttribute("id");
            document.getElementById("restblocks").append(newer);

Bit if I do cloning outside scope it adds the element to html only once:

        let theblock = document.getElementById("theblock").cloneNode(true);
        document.getElementById("add").addEventListener("click", function(){
            let newer = theblock;
            newer.removeAttribute("id");
            document.getElementById("restblocks").append(newer);

What could be the reason?

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

0

Because when you clone outside you only ever make a single clone, and a Node can only exist in one place in a document. If you want to avoid the query inside the click handler you can query outside, but clone inside.

let theblock = document.getElementById("theblock");

document.getElementById("add").addEventListener("click", function(){ 
  let newer = theblock.cloneNode(true);
  ...
});

const theblock = document.getElementById('theblock');
const restblocks = document.getElementById('restblocks');

document.getElementById('add').addEventListener('click', function () {
  let newer = theblock.cloneNode(true);

  newer.removeAttribute('id');
  newer.classList.remove('hidden');

  restblocks.append(newer);
});
.block { width: 40px; height: 40px; margin: 4px; background-color: pink; }
.hidden { display: none; }
<button type="button" id="add">Add a block</button>
<div id="restblocks"></div>

<div id="theblock" class="block hidden"></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