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

143
Visualizações
cloneNode without losing event listener

how can i move my html element without losing the event listener attached to the button?

The child button's event listener does not work after cloning and removing the original element

ul.appendChild(element.cloneNode(true));
element.remove();
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You've said you want to move it, but what you're doing is cloning it, saving the clone, and then removing and throwing away the original. Instead, don't clone it, move it:

ul.appendChild(element);

That will remove element from its current parent and put it in its new parent (ul), with all event listeners still in place.

Live Example:

// NOTE: This isn't how I'd write this code if I weren't demonstrating
// the fact the listeners are retained when the element is moved.
// But without context, it's hard to show a delegation solution.

const list1 = document.getElementById("list1");
const list2 = document.getElementById("list2");

// Add a listeneer to each `li`
document.querySelectorAll("li").forEach((li, index) => {
    li.addEventListener("click", () => {
        console.log(`Moving "${li.textContent}" which was originally at index ${index}`);
        if (li.closest("ul") === list1) {
            // Move from list1 to list2
            list2.appendChild(li);
        } else {
            // Move from list2 to list1
            list1.appendChild(li);
        }
    });
});
li {
    cursor: pointer;
}
<div>List 1:</div>
<ul id="list1">
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
</ul>
<div>List 2:</div>
<ul id="list2">
    <li>Item 4</li>
    <li>Item 5</li>
    <li>Item 6</li>
</ul>
<div>Click an item to move it to the other list.</div>


That said, I often find event delegation to be best when working with elements that move between parents, but it really depends on the situation.

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