I have a series of horizontal lists within one vertical list. Each list item has an ID 'cr-id-x_y' where x is the vertical list item index and y is the horizontal list item index. I have created a for loop within a for loop to determine which list item has been targeted. The problem I'm having is the button presses seem to be firing twice (i.e. I'm seeing "Hello world" printed to the console twice on a button press). Please can someone tell me where I'm going wrong?
document.getElementById("parent-list").addEventListener("click", function (e) {
for (let x = 0; x < 100; x++) {
for (let i = 0; i < 30; i++) {
if (
e.target.closest(`#cr-id-${x}_${i}`) &&
(e.target.nodeName == "BUTTON" ||
e.target.parentElement.nodeName == "BUTTON")
) {
console.log("Hello world");
}
}
}
});
From the code you posted, it is not possible to guess why it is firing twice, but actually there is no need to loop at all. When you delegate like you do, you should be able to interrogate the clicked target - for example like this
document.getElementById("parent-list").addEventListener("click", function(e) {
const tgt = e.target; // or if nested e.target.closest('button'), then use tgt in the next if
if (tgt.tagName==="BUTTON") {
const someParent = tgt.closest('someElementThatMightHaveCRId');
if(someParent.id && someParent.id.startsWith('cr-id-')) {
console.log("Hello world",someParent.id);
}
}
})