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

179
Visualizações
How to insert new elements with event listeners?

The goal is to fire an event by clicking on an element, which would create a new element with the same tag, classes and event listener to create another element of the same kind...

const btn = document.querySelectorAll("button");

btn.forEach((b) =>
  b.addEventListener("click", function () {
    console.log("Boom!");
    b.insertAdjacentHTML("afterend", "<button class='button'>Boom</button>");
  })
);
<button class="button">Boom</button>

However, when a new element is dynamically created it lacks event listener despite apllying .querySelectorAll and .forEach. So how would I dynamically create elements with event listeners?

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

0

One solution in my mind is to add a class (say myBtnEvent) to all the buttons and dynamic buttons and listen to click event at document level. Ex: Boom

document.addEventListener('click', function(event) {
    if(event.target && event.target.classList.contains('myBtnEvent')){
          //do your stuff
     }
 });

about 4 years ago · Juan Pablo Isaza Relatório

0

You can use cloneNode for that.

function duplicate(id) {
  const el = document.getElementById(id)
  const duplicateEl = el.cloneNode(true)
  const random = parseInt((Math.random() * 10000));
  duplicateEl.id = id + "_" + random; // unique ID
  el.insertAdjacentElement("afterend", duplicateEl)
}
<button id="boom" class="button" onclick="duplicate(this.id)">Boom</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