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

303
Visualizações
Javascript - get button data attribute value, push into array and calculate

Lurker and new to posting here.

I'm looking for a solution to this:

<a points="0" href="#" class="btn">Button Text</a>
<a points="1" href="#" class="btn">Button Text</a>
<a points="2" href="#" class="btn">Button Text</a>

<div class="success"></div>
<div class="failure"></div>

I need to find a way for a function/loop, to add the data attribute value (points) into an array, and calculate that if the result is >3 to show the "success" div, else to hide it and show the "failure" div.

I've no idea where to start honestly here and would appreciate help. I searched online for some results to put some code together but there wasn't too much on grabbing data attribute value on click and pushing it into an array.

Thanks in advance!

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

From my comments:

  • use data-points to adhere to standard. points is not a standard attribute
  • Also on what event do you add? Why do you need to add if you already know the number on the server? –
  • Lastly look at classList.toggle:

let result = [];
document.addEventListener("click", function(e) {
  const tgt = e.target;
  if (tgt.classList.contains("btn")) {
    result.push(+tgt.dataset.points)
  }
  if (tgt.id === "last") {
    const sum = result.reduce((a, b) => a + b)
    document.querySelector('.success').classList.toggle('hide', sum < 3)
    document.querySelector('.failure').classList.toggle('hide', sum >= 3)
  }
})
.hide {
  display: none;
}
<a data-points="0" href="#" class="btn">Button Text</a>
<a data-points="1" href="#" class="btn">Button Text</a>
<a data-points="2" href="#" class="btn">Button Text</a>
<a data-points="3" href="#" id="last" class="btn">Button Text</a>
<div class="success hide">Success</div>
<div class="failure hide">Failure</div>

Old answer:

let sum = [...document.querySelectorAll('a[data-points]')]
  .map(anchor => +anchor.dataset.points)
  .reduce((a, b) => a + b)

document.querySelector('.success').classList.toggle('hide', sum < 3)
document.querySelector('.failure').classList.toggle('hide', sum >= 3)
.hide {
  display: none;
}
<a data-points="0" href="#" class="btn">Button Text</a>
<a data-points="1" href="#" class="btn">Button Text</a>
<a data-points="2" href="#" class="btn">Button Text</a>
<a data-points="3" href="#" class="btn">Button Text</a>
<div class="success">Success</div>
<div class="failure">Failure</div>

about 4 years ago · Juan Pablo Isaza Relatório

0

points is not any attribute. For custom attributes use data-*, hence data-points.

Here is a basic example (based on assumptions) as to how you should go about it.

let newArr = [...document.querySelectorAll('a')];

let sum = newArr.reduce((cum,x) => {
        return cum + Number(x.getAttribute('data-points'));
},0);

console.log(sum);

if(sum > 3){
 document.querySelector('.success').style.display = 'block';
 document.querySelector('.failure').style.display = 'none';
}
else{
document.querySelector('.success').style.display = 'none';
document.querySelector('.failure').style.display = 'block';
}
<a data-points="0" href="#" class="btn">Button Text</a>
<a data-points="1" href="#" class="btn">Button Text</a>
<a data-points="2" href="#" class="btn">Button Text</a>
<a data-points="3" href="#" class="btn">Button Text</a>
<div class="success">Success</div>
<div class="failure">Failure</div>

  1. Get all relevant a elements using querySelectorAll.
  2. Compute the sum using reduce and getAttribute
  3. Use style.display to modify the styles.
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