Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

252
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!