Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

My delete eventListener is not deleting my items fom my array in javascript

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading