Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

127
Views
Vanilla js event handler not binding to dynamically created element

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.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!