Apologies for not originally having a reproducible test case - I have now made one on CodePen:- https://codepen.io/cssgrid/pen/971328c046d97ffd24decafa20804d3b/
I have a bunch of products. I want to remove the product from the DOM whenever someone clicks a remove button which is inside each product div. My problem is: the last product in the list is being removed rather than the product with the button in it that the user actually clicked :(
<div class="product">
//some code
<button class="remove-btn">Remove</button>
</div><!-- end of product div -->
var products = document.querySelectorAll(".product");
for (let i = 0; i < products.length; i++) {
products[i].addEventListener("click", function(e) {
if (e.target.classList.contains("remove-btn")) {
this.remove();
}
})
}
Also tried in jQuery:
$(".remove-btn").on("click", function() {
$(this).closest(".product").remove();
})