I am creating a todo app. I create add button which is working perfectly fine. But, the trash button it keeps on returning null value. I can not find solution on the google i didnt find the solution.
Can Anybody Help me here
var todoList = document.getElementById("todolist");
var addBtn = document.getElementById("add-btn");
var taskName = document.getElementById("task-name");
var trashBtn = document.getElementById("trash");
addBtn.addEventListener("click", addFunction);
function addFunction() {
var task = document.createElement("div");
task.classList.add("task");
var tname = document.createElement("li");
tname.setAttribute("id", "li-task");
var trash = document.createElement("BUTTON");
trash.setAttribute("id", "trash");
trash.innerHTML = '<i class="fas fa-trash"></i>';
tname.appendChild(trash);
task.appendChild(tname);
todoList.appendChild(task);
}
console.log(trashBtn);
console.log(addBtn);
Hi @ak95305. Welcome to FCC. I can see you are creating trash button in the event handler. Before clicking the button, there is no such element with id of trash. Therefore it is logical that you are getting null because the trashBtn variable is created immediately on page load.
That depends on what you want to do with it. But if you want to see its value console logged, first you can declare the variable like var trashBtn and inside the event handler, you can assign it to trashBtn after creating the button and assigning it an id .
If you console.log outside the event handler, it will only be console logged once on page load. You will continuing seeing null even after assigning the newly created button in the event handler. Actually you can also use the value of trash. The one you created here var trash = document.createElement("BUTTON"); because it references the button you have created. You can add styles or event handlers there instead of re-assigning a variable defined outside.