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
AddEventListener is not getting into his callback function when click

I have a dynamic button that supposed to remove his parent element from the DOM. Because its dynamic, i warpped it with DOMContentLoaded and added for each button the EventListener with 'click'. Somehow, i dont get into the callback function (deleteTodo) when click. I'll happy to know what im doing wrong. Thanks :)

document.addEventListener('DOMContentLoaded', (event) => {


let deleteBtn = document.getElementsByClassName('delete-btn');
for( let btn of deleteBtn)
    btn.addEventListener('click', deleteTodo);

});

// Delete element
const deleteTodo = () => {

console.log("inside function"); // I DONT GET INTO THIS LINE WHEN CLICK

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

0

You can't call a function assigned to a variable that hasn't been initialised. Use a function declaration (they're automatically hoisted) rather than a function expression so you can ensure that when your code tries to add the function to the listener it's actually available. And, as you can see from the example, it doesn't matter where you add the declaration.

function addThings() {
  const html = [];
  for (let i = 0; i < 5; i++) {
    html.push(`<div>${i}&nbsp;<button class="delete-btn">Delete</button></div>`)
  }
  return html.join('');
}

document.body.innerHTML = addThings();

const buttons = document.querySelectorAll('.delete-btn');

buttons.forEach(button => {
  button.addEventListener('click', deleteTodo, false);
});

function deleteTodo() {
  this.parentNode.remove();
}

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