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

249
Vistas
Removing the item with onClick and eventListener

In the JS code, there is a part which prints some number of items, and next to each item there is an icon for removing the item next to it:

 <img src="images/remove.png"  class="remove" onClick="remove_item(${index})"> 

So, when the user clicked a bin the item next to it will be removed by the function below. The point is that items are need to be stored in an array called list. So item will be removed from list. The function render is for printing the items again.

function remove_item(index) {
  list.splice(index, 1);
  localStorage.setItem('list', JSON.stringify(list));
  render(list); 

The code which is up is working perfectly. However the issue is that the task is needed to be done by using eventListener. For that img part is edited like below.

<img src="images/remove.png"  class="remove" data-index="${index}">

And the part which will remove the item from list is like below.

let remove = document.querySelectorAll(".remove"); 
Array.from(remove).forEach((el) => {
el.addEventListener('click', function() { 
    let index = el.getAttribute('data-index');
    list.splice(index, 1);
    render(list);
    localStorage.setItem('list', JSON.stringify(list));
})});

The problem is that, code is working only when page is refreshed before each click to any icon. So after clicking the icon, I have to refresh and then click again for removing some other item. How I can fix that?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

When you re-render the list the elements are all replaced, which strips the event handlers. You should probably just remove the actual element:

el.addEventListener('click', function() { 
    let index = el.getAttribute('data-index');
    list.splice(index, 1);
    el.remove();
    localStorage.setItem('list', JSON.stringify(list));
})});

Either that or run the code again after render which attaches the event handlers. Whatever makes the most sense with how you're rendering.

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