Search code examples
javascriptaddeventlistener

How to make an addEventListener for an element that does not render on page load work?


I have an input element that renders after you click a button, i.e., it does not render on page load. When a user types something into the element, it is supposed to console log "Add button clicked!". However, I get the below error message:

Uncaught TypeError: can't access property "addEventListener", document.getElementById(...) is null

Below is the code:

export const renderTodo = () => {
    document.querySelector('#main').innerHTML = `
<h2>Todo(CRUD) Page ${import.meta.env.VITE_TEST}</h2>
<br>
<form action="/action_page.php">
    <input type="text" placeholder="New todo.." id="new-todo">
    <br>
    <button id="add-todo">Add</button>
</form> 
`;
};

document.getElementById("new-todo").addEventListener("change", (e) => {
    console.log("Add button clicked!");
});

How do I get the addEventListener to work?


Solution

  • Error is throwing because as we are trying to access document.getElementById("new-todo") before it was attached to the HTML DOM as the function renderTodo() was not called and we tried to access the document.getElementById("new-todo").

    export const renderTodo = () => {
        document.querySelector('#main').innerHTML = `
    <h2>Todo(CRUD) Page ${import.meta.env.VITE_TEST}</h2>
    <br>
    <form action="/action_page.php">
        <input type="text" placeholder="New todo.." id="new-todo">
        <br>
        <button id="add-todo">Add</button>
    </form> 
    `;
    // after the HTML string is parsed and attached in DOM then apply. It will be called whenever the function is called.
      document.getElementById("new-todo").addEventListener("change", (e) => {
          console.log("Add button clicked!");
      });
    };