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

212
Visualizações
Adding an 'onclick' event to a button created by javascript

i have a card that is created every time a button is pressed, one of the parts of the card is the remove icon. I want to remove the card when the remove button is clicked. i am using this code:

let icon = document.createElement('span');
    icon.className = "span_x";
    document.getElementsByClassName('close')[0].appendChild(icon);
    document.getElementsByClassName('span_x')[0].innerHTML = '<i class="fa fa-remove"></i>';
    icon.addEventListener('click', removeTask());

i tried the last line of code in a few ways, like:

icon.onclick = function()
icon.setAttribute("onclick","removeTask()");

but whatever i'm trying, it always runs the function when creating the card (task), even though i didn't clicked on the icon. i hope i'm being clear enough. thank you for your help.

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

0

Try this:


xBtn.addEventListener('click', removeTask);

about 4 years ago · Juan Pablo Isaza Relatório

0

You need to remove the brackets. You're invoking the function right away, when you just need to pass a reference to it

icon.setAttribute("onclick", removeTask)

const removeTask = () => {
  console.log('clicked')
}

let icon = document.createElement('span');
icon.className = "span_x";
document.getElementsByClassName('close')[0].appendChild(icon);
document.getElementsByClassName('span_x')[0].innerHTML = '<i class="fa fa-remove"></i>';
icon.addEventListener('click', removeTask);
.close {
  width: 100px;
  height: 100px;
  background: green;
}

.span_x:after {
  content: 'Click'
}
<div class="close"></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