skip to Main Content

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?

2

Answers


  1. Call addEventListener() from inside the renderToDo block:

    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!");
    });
    };
    
    Login or Signup to reply.
  2. 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!");
      });
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search