Keep getting null value for button

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");
  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>';

<div class="main">
    <h1>Doer's List</h1>
  <div class="add-task">
      <input type="text" id="task-name">
      <button id="add-btn" type="button"><i class="fas fa-plus-circle"></i></button>
  <div class="to-do-list">
    <ul id="todolist"></ul>

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.

1 Like

So where should i put it?

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 .

trashBtn = document.getElementById("trash");

and then console.log(trashBtn).

I tried that too but keeps on giving null value
what i do now
i used lot of time finding the problem but i didnt get one

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.

1 Like

Thanks a lot for the help
A big thanks man

1 Like