Why JS Event handlers are not working for elements created at runtime?

Viewed 27

document.querySelector("#fire_button_creator_button").addEventListener("click",function () {
    document.querySelector("body").appendChild(document.createElement("button")).innerText="now click me,i am fire button";
})

document.querySelector("#fire_button_creator_button+button").addEventListener("click",function () {
    document.querySelector("p").innerText="i am fired";
})
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button id="fire_button_creator_button">fire button creator</button>
    <p></p>
</body>
</html>

I want to creat a button in runtime that can do somthing. Somthing like in my code it inject some text inside <p> </p> tag "i am fired". But i am getting errore. But why?. What is the solution(in vanilla javascript of course)?

2 Answers
document.querySelector("#fire_button_creator_button").addEventListener("click",function () {
    const button = document.createElement("button");
    document.querySelector("body").appendChild(button).innerText="now click me,i am fire button";
  
    button.addEventListener("click",function () {
        document.querySelector("p").innerText="i am fired";
    })
})

You have to add the event listener AFTER the new button element is created. You can do that like the code sample above or other way. The only important part is to do AFTER it is created, so an actual event listener is attached to an actual html element

You can just assign the eventListener to the createdElement immediately instead of selecting it again (which won't work in your case, as the element doesn't even exist yet).

document.querySelector("#fire_button_creator_button").addEventListener("click",function(){
    const button = document.createElement("button")
    button.innerText="now click me, i am fire button"
    button.addEventListener("click",function(){
       document.querySelector("p").innerText="i am fired";
    })
    document.querySelector("body").appendChild(button)
})
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button id="fire_button_creator_button">fire button creator</button>
    <p></p>
</body>
</html>

Related