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

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)?

>Solution :

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>

Leave a Reply