JavaScript - 23
JavaScript - 23: To-Do List with Delete Buttons
Improve the to-do list by giving every task its own Delete button.
Your challenge: Create a task, add a Delete button beside it, and remove that task when its button is clicked.
Create the task and button
Just like the previous lesson, create the task with: document.createElement("li")
Then create a button: document.createElement("button")
Set its text to Delete and give it the class delete-btn.
Add both elements to the page
Put the task text inside the <li>, then append the Delete button to that same list item.
Finally, add the finished <li> to todoList.
Delete one task
Add a click listener directly to the new Delete button.
Inside it, use: li.remove();
Because each button is connected to its own li, it removes only that task.
Try it: Add several tasks, then delete them in a different order.
Small experiment: Change the Delete button text to Remove or Done.
Good JavaScript habit: When displaying user-entered text, use textContent instead of building HTML with innerHTML.
👀 Show Solution
const taskInput = document.getElementById("taskInput");
const addBtn = document.getElementById("addBtn");
const todoList = document.getElementById("todoList");
addBtn.addEventListener("click", function() {
const task = taskInput.value.trim();
if (task === "") {
return;
}
const li = document.createElement("li");
const deleteBtn = document.createElement("button");
li.textContent = task;
deleteBtn.textContent = "Delete";
deleteBtn.className = "delete-btn";
li.appendChild(deleteBtn);
todoList.appendChild(li);
deleteBtn.addEventListener("click", function() {
li.remove();
});
taskInput.value = "";
taskInput.focus();
});Each task gets its own Delete button. Clicking that button runs li.remove(), which removes only the matching list item.
