2

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?

Saad
  • 33
  • 5
  • [This is probably relevant](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements). There's a strong focus on jQuery in that question, but some answers provide plain JavaScript solutions. – David Aug 28 '23 at 19:43

2 Answers2

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!");
  });
};
Jerry
  • 1,005
  • 2
  • 13
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!");
});
};
user3163495
  • 2,425
  • 2
  • 26
  • 43