Sackadelic
Sackadelic

Reputation: 1019

QuerySelectorAll returning an empty nodelist with OOP

I'm rebuilding a todo list app and trying to work with Object Oriented Programming, which is new to me. I've got the task section built, but I am getting stuck on locating the "delete" buttons. When adding a new task, a font awesome icons show to the right. I'm trying to select them, but I am getting an empty nodelist each time the function runs:

Codepen: To Do List

To reproduce:

Add a task, and check the console. You'll see an empty nodelist.

What I've tried:

Right now, I'm trying to simply console.log the element. I'm running console.log(buttons) Each time the addTask() method runs.

Here's the full JS:


const submit = document.querySelector("#commit-task"),
  results = document.querySelector("#task-results"),
  input = document.querySelector("#input-task"),
  buttons = document.querySelectorAll(".fa-times");  // These are what I'm trying to select

class Task {
  constructor(task) {
    this.taskText = task;
  }

  addTask() {
    const text = input.value;
    ui.clearInput();

    const taskBody = `<div class="task">
        <span>${text}</span>
            <span>
              <i class="fas fa-check" style="color: green;"></i>
              <i class="fas fa-times" style="color: red;"></I> //This is the element I'm trying to select
            </span>
    </div>`;

    results.innerHTML += taskBody;

    console.log(buttons); //Here's where the Console.log statement is run
  }
}

class UI {
  clearInput() {
    input.value = "";
    input.focus();
  }
}
const newTask = new Task();
const ui = new UI();

// Add Event Listeners:

submit.addEventListener("click", () => {
  newTask.addTask(); //Here is when addTask() is run.
});

input.addEventListener("keyup", (e) => {
  if (e.keyCode === 13) {
    newTask.addTask();
  }
});

Why does JavaScript think these buttons are not in the DOM? Thanks in advance.

Upvotes: 2

Views: 13123

Answers (1)

Berk Kurkcuoglu
Berk Kurkcuoglu

Reputation: 1523

document.querySelectorAll(".fa-times"); gets executed during the first assignment and as there are no icons during the time of initialization, buttons are equal to an empty NodeList.

In order check the current status you need to re run the query.

Just declare buttons as let buttons = document.querySelectorAll(".fa-times");

Then re-run the query and assign it's latest result to your buttons variable before logging it:

buttons = document.querySelectorAll(".fa-times");
console.log(buttons);

Upvotes: 7

Related Questions