Bound Event listener doesn't trigger after changing DOM element

January 27, 2024

© 2024 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui(2024-01-27 11:43:26 +0000). Bound Event listener doesn't trigger after changing DOM element. https://borui/blog/2024-01-27-en-event-listener-rebinding.
@misc{
  borui2024,
  author = {borui},
  title = {Bound Event listener doesn't trigger after changing DOM element},
  year = {2024},
  publisher = {borui's blog},
  journal = {borui's blog},
  url={https://borui/blog/2024-01-27-en-event-listener-rebinding}
}

I encountered this when I use below code to append elements to body.

    let p = document.createElement("p");
    p.innerHTML = `some text`
    document.body.appendChild(p);

Below is the js and html I use to bind click event on a button.

    <body>
        <h1>Hello, World!</h1>
        <button id="btn">click</button>
    </body>

    <script>
        const btn = document.getElementById('btn');
        btn.addEventListener('click', () => {})
    </script>

After appending the elements, the button lost binding for the click event.

To fix this, I simply used onclick like below

    <button id="btn" onclick="btnHandler()">click</button>