🛠️ Todolist: Deleting tasks with JavaScript

Hey ,

I'm thrilled to help you learn JavaScript. Unfortunately, you've landed on a page where you cannot access with your current purchase.

Please upgrade (use this link) access this content.

I'm super eager to help you learn more!

🛠️ Todolist: Deleting tasks with JavaScript

When a user clicks the delete button, we want to delete the corresponding task.

The task gets deleted when user clicks on the delete button

Deleting tasks

A Todolist contains many tasks. Each task contains a delete button. In this case, the best way to delete a task is to use an event delegation pattern.

todolist.addEventListener('click', event => {
  // Deletes a task
})

We only want to activate the event listener if the user clicks on the delete button. We bail if the clicked element is not a delete button.

todolist.addEventListener('click', event => {
  if (!event.target.matches('.task__delete-button')) return
  // Deletes a task
})

If the user clicks on the delete button, we want to find the task element to remove. The task element is the parent element of the delete button.

todolist.addEventListener('click', event => {
  if (!event.target.matches('.task__delete-button')) return

  // Deletes a task
  const taskElement = event.target.parentElement
})

We can use removeChild to delete a task. This means we need to know what’s the parentElement of the task too.

todolist.addEventListener('click', event => {
  if (!event.target.matches('.task__delete-button')) return

  // Deletes a task
  const taskElement = event.target.parentElement
  taskList.removeChild(taskElement)
})
The task gets deleted when user clicks on the delete button

Triggering the empty state

We want to trigger the empty state if there are no more tasks in the .todolist__tasks. This empty state can only be triggered if there are no whitespaces in the HTML (because of the way we built it).

Each time we delete a task, we want to check if there are any tasks left in the taskList. If there are no tasks left in the taskList, we set the innerHTML to '' to remove all whitespace.

todolist.addEventListener('click', event => {
  if (!event.target.matches('.task__delete-button')) return

  const taskElement = event.target.parentElement

  // Removes the task
  taskList.removeChild(taskElement)

  // Triggers empty state
  if (taskList.children.length === 0) {
    taskList.innerHTML = ''
  }
})
Empty state shows up when no tasks are left

That’s it!