My addEventListener only works when I click the image twice. The console log does say that the item has been deleted from the database, I see this as well in the array. This means that the function works, but why does it take two times to actually delete the item from the DOM?
const addToDom = async (data) => {
const item = document.createElement("li");
item.innerHTML = '';
data.forEach((task) => {
const deleteImage = document.createElement('img');
const toDoList = document.getElementById("todo-list");
deleteImage.id = task._id;
item.classList.add("task-item");
deleteImage.src = 'bin.png';
item.innerHTML = task.description;
toDoList.appendChild(item);
item.appendChild(deleteImage);
deleteImage.addEventListener("click", (event) => {
const idToDelete = event.target.id;
toDoList.removeChild(item);
item.innerHTML = '';
console.log(`Delete ${task.description}`);
deleteData(idToDelete);
loadData(data);
});
});