i'm building a project for my boot camp, and i'm stuck in a small quite annoying area. i have an api where i can make queries to amazon and display products, each product has its own "card" styling and along with it i push each product to an empty array inside the user class constructor if the user select that he wants to add that product to his "profile", within the user class i have a function called "displayProducts" which basically iterating over that products array, creating a div element, modifying the innerHTML of the element on each iteration and displaying it on the page. this is the function:
const productSection = document.getElementById('userProducts')
productSection.innerHTML = ``;
let div = document.createElement('div')
if (user.products.length > 0) {
user.products.forEach((product) => {
div.innerHTML += `
<div class="card horizontal">
<div class="card-image">
<img src=${product.img}>
</div>
<div class="card-stacked">
<div class = "card-content">
<span class = "card-title"> ${product.title} </span>
<p> ${product.rating} rating, ${product.totalReviews} reviews </p>
<span> Price:${product.price}</span>
</div>
<div class="card-action">
<button class="btn delete-${product.asin}">delete</button>
</div>
</div>
`
deleteButton = div.querySelector(`.delete-${product.asin}`).addEventListener('click', user.delete.bind(product))
productSection.appendChild(div);
}
The problem is, while adding the event listener to each button - it's af it's only applying the event listener to the last product, even though on each stage it select the correct button, i have been at it for over two hours and i'm quite lost. How do i persist an event listener to each product card?