RE: Event binding on dynamically created elements?

John Q Reviewer Asked on August 14, 2019 in Code.
Add Comment
2 Answers
var iterations = 4;
var button;
var body = document.querySelector("body");

for (var i = 0; i < iterations; i++) {
    button = document.createElement("button");
    button.classList.add("my-button");
    button.appendChild(document.createTextNode(i));
    button.addEventListener("click", myButtonWasClicked);
    body.appendChild(button);
}

function myButtonWasClicked(e) {
    console.log(e.target); //access to this specific button
}
Trainee Answered on August 14, 2019.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.