I am currently working on a mini web application and would like some advice. I know the reason for my issue and I know one way to get around it but it would mean undoing a lot of the work that I have already done.
The issue I have is I am currently using a template string inside a for loop to print data and I have a delete button with a listener. Currently it is only working for the last button the in the list and I know it is because I am destroying the innerHTML every time I use html = x.
What I would like to know is....is there an easy way around this or should I just use append child etc instead?
for(let prod of products){
console.log("Doc ID",doc.id);
const li1 = `
<p><div>${prod.name} <div class="right"><font class=pink-text>Location:</font> $${prod.location} <button data-remove-button-id="${doc.id}" class="btn-remove">Delete</button></div></div></p>
`;
html += li1;
} //end for loop
const li2 = `
<br />
<button class="btn blue darken-2 z-depth-0 right modal-trigger" data-target="modal-prodedit">Add/Edit Attributes</button><br />
</div>
</li>
`;
html += li2;
productList.innerHTML = html;
const removeBtn = document.querySelector(`[data-remove-button-id="${doc.id}"]`);
console.log("removeBTN",removeBtn);
removeBtn.addEventListener('click', (e) => {
e.preventDefault();
console.log(`deleted row ${e.target.dataset.removeButtonId}`);
});
You are using querySelector() method which returns the first element it finds. If you want to attach that listener to all rows you need to use Document.querySelectorAll(). You'll need to differentiate between which row was selected, which doesn't seem to be in your DOM model. So I'd add a data-product-id
attribute to your button, and the listener can use that to know which product was deleted.