Basic Task Management
12 min read
Delete a Task
Delete a Task
The final feature in this module is task deletion.
1. Add the Delete Button
Inside renderTasks(), update the task HTML so it includes a delete button:
taskElement.innerHTML = `
<div class="task-main">
<button
class="task-check"
type="button"
data-action="toggle"
data-id="${task.id}"
aria-label="${task.completed ? "Mark task active" : "Complete task"}"
></button>
<span class="task-title">${task.title}</span>
</div>
<button
class="task-action task-delete"
type="button"
data-action="delete"
data-id="${task.id}"
aria-label="Delete task"
>
Delete
</button>
`;
Keep the existing completed-state code after this HTML.
2. Add the Delete Handler
In the same taskList click listener, add this block before the existing toggle code or handle both actions together:
const action = event.target.closest("[data-action]");
if (!action) {
return;
}
const taskId = action.dataset.id;
if (action.dataset.action === "delete") {
const taskIndex = tasks.findIndex((item) => item.id === taskId);
if (taskIndex !== -1) {
tasks.splice(taskIndex, 1);
renderTasks();
}
return;
}
Keep the existing toggle handling for data-action="toggle".
3. Test Deletion
Add several tasks.
Delete one task.
The selected task should disappear while the remaining tasks stay in the list.
Complete a task and then delete it. It should still be removed correctly.
Checkpoint
The basic task workflow is now complete:
- Add a task
- Display tasks
- Complete a task
- Reopen a completed task
- Delete a task
These are the core operations we will build on in the next modules.