0

I am learing basics of JavaScript and I have coded a simple shopping list with a delete button. This option works with old items, but when I add a new one and try to delete it, it does not work properly.

HTML:

var lista = document.querySelector('#list')
document.getElementById('add').addEventListener('click', function() {

  var deletebtn = "<span class='close'>X</span>"
  var newValue = document.getElementById('new_item').value + ' ' + deletebtn;
  var newItem = document.createElement('li');
  newItem.innerHTML = newValue;
  lista.appendChild(newItem);

}, false)

var closebtn = document.getElementsByClassName('close');
for (var i = 0; i < closebtn.length; i++) {
  closebtn[i].addEventListener('click', function() {
    this.parentElement.style.display = 'none';
  })
}
<div id=”page”>
  <h1 id=”header”>Shopping list</h1>
  <h2>What should I buy</h2>
  <ul id="list">
    <li id="one">Milk<span class="close">X</span></li>
    <li id="two">Apples<span class="close">X</span></li>
    <li id="three">Oranges<span class="close">X</span></li>
    <li id=”four”>Vodka<span class="close">X</span></li>
  </ul>
  <input type="text" placeholder="Type in a new item" id="new_item"><button id='add'>ADD</button>
</div>
Calvin Nunes
  • 6,376
  • 4
  • 20
  • 48
  • 1
    Does this answer your question? [JavaScript querySelector versions of Jquery](https://stackoverflow.com/questions/56400619/javascript-queryselector-versions-of-jquery) – Taplar Feb 21 '20 at 18:39
  • Specifically https://stackoverflow.com/a/56400958/1586174 covers a delegate version of an event binding in vanilla javascript. – Taplar Feb 21 '20 at 18:40
  • 1
    Does this answer your question? [Attach event to dynamic elements in javascript](https://stackoverflow.com/questions/34896106/attach-event-to-dynamic-elements-in-javascript) – Calvin Nunes Feb 21 '20 at 18:42
  • The issue is that when you add a new item to the list, the for loop that add the click event to all close buttons were already run and so it'll never bind the event to new items. What you need to do is to add the event listener foreach new item you add to the list as soon as you do so. – Cadu De Castro Alves Feb 21 '20 at 18:43

1 Answers1

3

It's because your new item does not have the click event listener attached.

Add event listener for the close button like this:

var deletebtn = document.createElement('span');
// ...add class, inner html...
deletebtn.addEventListener('click', deleteFunc);

Also, make your delete function a reusable function and attach it like this:

function deleteFunc() {
    this.parentElement.style.display = 'none';
}

...
  closebtn[i].addEventListener('click', deleteFunc)
...
technophyle
  • 7,972
  • 6
  • 29
  • 50