My app has a list. a list of rules. When deleting a rule from the list usually works as expecte. except when deleting the very first rule on the list the event triggers again. This behaviour is odd and I couldnt find a clear explanation why. Hope someone could help me out here
document
.querySelector("#rules-list")
.addEventListener("click", async (event) => {
if (event.target.closest("#rule-edit-button")) {
// not relevent here
} else if (event.target.closest("#rule-delete-button")) {
event.stopPropagation();
const deleteButton = event.target.closest("#rule-delete-button");
const index = deleteButton.getAttribute("data-index");
console.log({ allRules, index }); //1
if (allRules.length > index) {
console.log(allRules[index]);
allRules.splice(parseInt(index), 1);
console.log({ allRules, index }); //2
allConditions = [];
allConditions = allRules;
document.querySelector(`#rule-item-${index}`).remove();
}
}
});
and when i inspect the console logs i see the console log mared with the comment // 1
repeating after removing the element from dom. something that is evenmore odd is that when the event triggers again the second time this code runs it has the same index value 0
when the element is supposed to have been removed from the dom in other words deleteButton
and index
should be null when the event gets triggered second time. but they are not and i have verified with the browser debug that document.querySelector(
#rule-item-${index}).remove();
this line actually runs and it actually removes the element from DOm.
Could someone help me out i am not sure what i am missing here
PS. I also tried removing async keyword from the event function
`