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

129
Visualizações
Vanilla js event handler not binding to dynamically created element

I've seen a few other posts on this but I haven't been able to find anything that matches the problem I'm having. It's a basic to do list with vanilla js

let x = document.querySelectorAll(".x");
let li = document.querySelectorAll("li");
let ul = document.querySelector("ul");
let add = document.querySelector(".add");
let input = document.querySelector(".input");
let span = document.querySelector("span");


add.addEventListener("click", () => {
  const newLi = document.createElement("li");
  ul.appendChild(newLi);
  let newSpan = document.createElement("span");
  newSpan.classList.add("x");
  newSpan.innerText = "X";
  newLi.innerHTML = input.value;
  newLi.appendChild(newSpan);
});

for (let i = 0; i < x.length; i++) {
    x[i].addEventListener("click", (e) => {
      if (e.target.classList.contains("x")) {
        e.target.parentNode.remove("li");
      }
    });
  }

I thought I was being clever with the for loop to select all the class names of ".x" then using that to remove the parent node of "li".

the issue here is when I'm adding a new item to the list the event handler is not being applied to it.

I looked up some event delegation but it doesn't seem to be working. any suggestions are appreciated.

about 4 years ago · Juan Pablo Isaza
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