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.