CodingNic

Task Actions

Delete a Task

Task Actions 18 min read

Delete a Task

Delete a Task

Each generated card already receives a task ID through data-id. Use that ID to tell JavaScript exactly which task should be removed.

Add a delete button when you create the card. Give it a class that is easy to target:

javascript
const deleteButton = document.createElement("button");
deleteButton.type = "button";
deleteButton.className = "delete-task";
deleteButton.textContent = "Delete";

Append it to the card.

Instead of adding a separate listener to every card after rendering, handle the click from the board using event delegation. Select the board once:

javascript
const board = document.querySelector(".board");

Inside the click handler, find the closest delete button and then the card’s ID:

javascript
board.addEventListener("click", (event) => {
  const button = event.target.closest(".delete-task");
  if (!button) return;

  const card = button.closest(".task-card");
  const id = Number(card.dataset.id);

  tasks = tasks.filter((task) => task.id !== id);
  renderTasks();
});

Use the actual board/card selectors from your starter if they differ.

The important part is the state change:

text
click delete
    ↓
find task id
    ↓
remove from tasks
    ↓
renderTasks()

Checkpoint

Create two tasks. Delete one.

The selected card should disappear and its column count should decrease. Refreshing is not expected to preserve the deletion yet; persistence comes later in the course.