0

so I try to make some simple content of modal window as a shopping cart only using js, and there is a problem with delete of each item by "x" after I add them on the cart, I use event.target, but at that stage it gives me an error as "null", it is in the last row of the code. Dont be strict, its my first code :) so each time I insert in cart

cartItems.innerHTML += `<div class="modal-items-flex ">
<div>
<h2> Item Price: ${itemPrice} </h2>
<h2 class="underscore">Item Name: ${itemTitle} </h2>
</div>
<div class="modal-item-delete">+</div>
</div>`

let removeButton = document.querySelector(".modal-item-delete");

removeButton.onclick=function(e){                               
  e.target.parentElement.remove();
} 

1 Answers1

0

I would not attach a new event-listener to each item, but instead would delegate the event-handling to the parent, for example:

cartItems.addEventListener('click', (e) => {
  const btn = e.target.closest('.modal-item-delete');
  if (!btn) return;
  btn.parentElement.remove();
});
Andre Nuechter
  • 1,763
  • 8
  • 15
  • thanks, but for what `if (!btn) return;` is here? it works without it aswell. – Aram Harutyunyan Jun 05 '20 at 08:39
  • @AramHarutyunyan This line is a safe guard, because the line below will throw an error if you click on an element outside a delete-button, since then `btn` would be null. – Andre Nuechter Jun 06 '20 at 01:35
  • ah, I hide the context of modal if the main close of modal window is closed, so there is no such risks, but anyway, lets have double guard, thanks. – Aram Harutyunyan Jun 06 '20 at 17:47
  • @AramHarutyunyan The listener will trigger on every click inside the `cartItems` element, including those not inside a delete-button, which means the call to `closest` will not find an element then, causing a type-error when trying to remove the parent of _null_. The code works without the guard, but is less safe and that may cause you head-aches down the line. – Andre Nuechter Jun 06 '20 at 18:48