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
Call
addEventListener()
from inside therenderToDo
block:Error is throwing because as we are trying to access
document.getElementById("new-todo")
before it was attached to the HTML DOM as thefunction renderTodo()
was not called and we tried to access thedocument.getElementById("new-todo")
.