Skip to main content

Exercise 30: Create a To-Do List with data-id and remove()

Learn how to remove tasks from a list in JavaScript using data-id and remove(). This is an excellent exercise for manipulating the DOM. The main goal is to practice handling DOM events by creating a to-do list where each task can be removed using data-id.e.target.dataset.idto identify it.

Activity

  1. Create an HTML list with some tasks and a "Delete" button next to each task. Each task must have an attributedata-idUnique.

  2. When you click the "Delete" button, identify the task to be deleted usinge.target.dataset.idand remove only that task from the DOM.

  3. Ensure that the event only affects the "Delete" button and not the rest of the container.

Solution

Step 1: Create the index.html file

HTML
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Crear una Lista de Tareas con data-id y remove()</title>
</head>
<body>
<h1>Ejercicio 30: Crear una Lista de Tareas con data-id y remove()</h1>

<ul id="taskList">
<li data-id="1">Tarea 1 <button class="deleteBtn">Eliminar</button></li>
<li data-id="2">Tarea 2 <button class="deleteBtn">Eliminar</button></li>
<li data-id="3">Tarea 3 <button class="deleteBtn">Eliminar</button></li>
</ul>

<script src="script.js"></script>
</body>
</html>

Step 2: Write the code in script.js

JavaScript
// Seleccionar la lista de tareas y agregar evento al botón de eliminar
document.getElementById("taskList").addEventListener("click", (e) => {
if (e.target.classList.contains("deleteBtn")) {
// Obtener el id de la tarea usando dataset.id
const taskId = e.target.parentElement.dataset.id;
console.log(`Eliminando tarea con ID: ${taskId}`);
// Eliminar la tarea del DOM
e.target.parentElement.remove();
}
});
info

🔎Review the following sections where you will find more information on this topic:

Control instructions in JavaScript

Local Storage in JavaScript

DOM Events in JavaScript