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

127
Visualizações
Im having problems to retrieve the data attributes

I'm trying to retrieve the data attributes from the cart but it's not working.

I also would like to know if there's a way to shorten the code.

HTML:

<div id="product-listing" class="hidden">
  <div>
    <img src="img1.jpg" />
    <div class="description">Lagavulin 16 Year Old</div>
    <button class="add-to-cart"
            data-product-id="1"
            data-product-title="Lagavulin 16 Year Old" data-category="Scotch">
            Add To Cart
    </button>

Vanilla js:

function onPageLoad(event) {
  var title = document.getElementsByTagName("title")[0].innerText;
  console.log({
    event_name: "page loaded",
    page_title: title,

  });
}

var photo = document
  .getElementsByClassName("add-to-cart")
  .getAttribute("data-product-id");

for (var i = 0; i < photo.length; i++) {
  photo[i].onclick = function() {
    console.log({
      event_name: "add_to_cart",
      product_id: data-product-id,
      product_title: data-product-title,
    });
  }
};
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

This should work:

Array.from(document.getElementsByClassName("add-to-cart")).forEach(x => x.onclick = () => console.log({
  event_name: "add_to_cart",
  product_id: x.getAttribute("data-product-id"),
  product_title: x.getAttribute("data-product-title")
}));
<button class="add-to-cart" data-product-id="1" data-product-title="Lagavulin 16 Year Old" data-category="Scotch">Add To Cart</button>

<button class="add-to-cart" data-product-id="2" data-product-title="Some other Scotch" data-category="Scotch">Add To Cart</button>

You were not properly iterating over the elements returned by getElementsByClass and also not using element.getAttribute("") correctly.

To make it shorter I used streams.

about 4 years ago · Juan Pablo Isaza Relatório

0

Try this way:

var photo = document
  .getElementsByClassName("add-to-cart");

for (var i = 0; i < photo.length; i++) {
  photo[i].onclick = function() {

    console.log({
      event_name: "add_to_cart",
      product_id: photo[i].getAttribute("data-product-id"),
      product_title:  photo[i].getAttribute("data-product-title"),
    });
  }
};
about 4 years ago · Juan Pablo Isaza Relatório

0

Try this

var photo = document.querySelectorAll('.add-to-cart');
photo.forEach(function(button){
    button.addEventListener('click',function(){
        console.log(this.getAttribute('data-product-id'));
    },{passive:true});
});
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