Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

202
Vistas
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 Respuestas
Responde la pregunta

0

Try this:


xBtn.addEventListener('click', removeTask);

about 4 years ago · Juan Pablo Isaza Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda