Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading