0

I've seen a few other posts on this but I haven't been able to find anything that matches the problem I'm having. It's a basic to do list with vanilla js

let x = document.querySelectorAll(".x");
let li = document.querySelectorAll("li");
let ul = document.querySelector("ul");
let add = document.querySelector(".add");
let input = document.querySelector(".input");
let span = document.querySelector("span");


add.addEventListener("click", () => {
  const newLi = document.createElement("li");
  ul.appendChild(newLi);
  let newSpan = document.createElement("span");
  newSpan.classList.add("x");
  newSpan.innerText = "X";
  newLi.innerHTML = input.value;
  newLi.appendChild(newSpan);
});

for (let i = 0; i < x.length; i++) {
    x[i].addEventListener("click", (e) => {
      if (e.target.classList.contains("x")) {
        e.target.parentNode.remove("li");
      }
    });
  }

I thought I was being clever with the for loop to select all the class names of ".x" then using that to remove the parent node of "li".

the issue here is when I'm adding a new item to the list the event handler is not being applied to it.

I looked up some event delegation but it doesn't seem to be working. any suggestions are appreciated.

Brandon.b
  • 147
  • 2
  • 9
  • In event delegation, you don’t bind multiple event listeners to individual targets, but a single event listener to a _common ancestor_. Also, `e.target.closest(".x")` is a more robust check. – Sebastian Simon Feb 08 '22 at 18:38
  • Right, so I'm not trying to bind multiple event listeners to an individual target when I try to add it to let's say "li" then none of them work afterwards. – Brandon.b Feb 08 '22 at 18:49

0 Answers0