Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

245
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda