A variable in an anonymous function under EventListener staying undefined despite being previously declared and then defined clearly
So I’m making a basic to-do list using only HTML and JS and for some reason, when I go to add an item to the list, the variable that I’m using to select the empty "li" element is returning as "undefined" after I execute the function under the EventListener for the "clear" button. Could someone help out here pls. HTML and JS attached below:
let todos = []; let add = document.querySelector("#add"); let remove = document.querySelector("#remove") let clear = document.querySelector("#clear") let todolist = document.querySelector("#todolist") let addTodo; let clearedTodo; let newTodo; add.addEventListener("click", function() { addTodo = prompt("Enter the item you would like to add.") todos.push(addTodo); todolist.innerHTML += "<li></li>" newTodo = document.getElementsByTagName("li")[todos.length - 1] newTodo.textContent = addTodo; }) remove.addEventListener("click", function() { let removeTodo = prompt("Enter the index number of the item you would like to remove.") - 1; let removedTodo = document.getElementsByTagName("li")[removeTodo] removedTodo.remove(); todos.splice(removeTodo, 1); }) clear.addEventListener("click", function() { todos = []; document.querySelector("ol").remove(); document.querySelector("div").innerHTML += '<ol id="todolist"></ol>' console.log("To Do list was cleared.") })
<h1>The Ultimate To Do List</h1> <p>Click on an item to mark as done.</p> <button id="add">ADD</button> <button id="remove">REMOVE</button> <button id="clear">CLEAR</button> <div id="clearer"> <ol id="todolist"> </ol> </div>
Thanks.
The problem is in your clear function. Mostly it looks good except for one problem that causes the major error. When you remove all the "ol" element, your todolist
var loses reference, since it has nothing to point to. You would have to redeclare it.
But there is an easier way to fix this. Remove these lines:
document.querySelector("ol").remove(); document.querySelector("div").innerHTML += '<ol id="todolist"></ol>'
Use this line instead:
todolist.innerHTML = "";
Now the todo list in the DOM is also cleared and your todolist
var still points to what its supposed to.