Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

241
Vistas
How to have the data-id of an element when you click on it?

I create several buttons and I give them an id in a loop and I would like that when we click on it, its id is displayed in the console. This is what I tried to do but the program returns the last id assigned after the loop.

for (var i = 0; i < 3; i++) {
var button = document.createElement('button');
button.textContent = "Add to cart"; 
button.setAttribute("data-id", i+1);
card.appendChild(button);
button.onclick = function() {
  let attribut = button.getAttribute("data-id");
  console.log(attribut)
};

}

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

When the onclick gets called, button is still set to the last button in your loop; there's no reference to button in your onclick. Instead, try passing the event (e) into the onclick, then reference the event's target with e.target.

for (var i = 0; i < 3; i++) {
  var button = document.createElement('button');
  button.textContent = "Add to cart"; 
  button.setAttribute("data-id", i+1);
  document.body.appendChild(button);
  button.onclick = function(e) {
    let attribut = e.target.getAttribute("data-id");
    console.log(attribut)
  };
}

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda