Exercise 28: Identifying Elements with dataset.id
Learn to identify dynamic HTML elements with dataset.id using JavaScript events. Ideal for interactive apps. The main objective is to learn how to usee.target.dataset.idto identify specific elements within a list. Practice event handling and the use of stored IDs indata-attributes
Activity
-
Create a list of buttons in HTML, and assign an attribute to each button.
data-idUnique. -
Clicking any of the buttons displays an alert that says:
"Has hecho clic en el botón con ID: [ID del botón]"using the value ofdata-id3. Usee.target.dataset.idto obtain the ID of the button that was clicked.
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>Identificar Elementos con e.target.dataset.id</title>
</head>
<body>
<button data-id="1">Botón 1</button>
<button data-id="2">Botón 2</button>
<button data-id="3">Botón 3</button>
<script src="script.js"></script>
</body>
</html>
Step 2: Write the code in script.js
JavaScript
// Seleccionar todos los botones
document.querySelectorAll("button").forEach((button) => {
button.addEventListener("click", (e) => {
// Obtener el data-id del botón clicado
const id = e.target.dataset.id;
alert(`Has hecho clic en el botón con ID: ${id}`);
});
});
info
🔎Review the following sections where you will find more information on this topic:
Control instructions in JavaScript
Array methods in JavaScript
DOM Events in JavaScript