I am trying to get my code to delete an item from an array and then stop displaying it on my html. However the item is not deleted when clicking on the item but rather when clicking on the x below it. When I do click on the x it deletes the last item in the array instead of the one I am clicking on. I used an event listener for the item to be deleted.
let myArray = ["Sugar", "Milk", "Bread", "Apples"];
let list1 = document.querySelector("#itemList");
displayList = (arr) => {
let items = arr.forEach(item => {
let li = document.createElement("li");
li.textContent = item;
list1.appendChild(li)
const deleteBtn = document.createElement("span");
deleteBtn.className = "close";
deleteBtn.textContent = "\u00D7";
list1.appendChild(deleteBtn);
deleteBtn.addEventListener("click", (event) => {
let click = event.target.LI;
console.log(click)
let index = arr.indexOf(click);
if (index < -1) {
arr.splice(index, 1)
}
list1.innerHTML = '';
displayList(arr)
})
})
}
displayList(myArray)
>Solution :
event.target will not have an LI property, because it is inside span.
Try this
displayList = (arr) => {
list1.innerHTML = ''; // Clear the list before re-rendering
arr.forEach((item, index) => {
let li = document.createElement("li");
li.textContent = item;
list1.appendChild(li);
const deleteBtn = document.createElement("span");
deleteBtn.className = "close";
deleteBtn.textContent = "\u00D7";
list1.appendChild(deleteBtn);
deleteBtn.addEventListener("click", () => {
arr.splice(index, 1); // Remove the item from the array
displayList(arr); // Re-render the list
});
});
};
displayList(myArray);