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

85
Visualizações
need help getting values from a click function in javascript

So I have a problem getting the ID's from my buttons. My code is only returning the id value from the first tic button and not the rest of them when I click on them.

here is the HTML:

<div class="row">
    <div class="col-lg-12">
        <a class="btn btn-lg btn-primary tic" id="0">#</a>
        <a class="btn btn-lg btn-primary tic" id="1">#</a>
        <a class="btn btn-lg btn-primary tic" id="2">#</a>
    </div>
</div>

and here is the javascript:

const tick = document.querySelector('.tic');

tick.addEventListener('click', () =>{
    var slot = tick.id;
    console.log(slot);
});

it only returns 0 when I click on the first button but it does not return 1 when I click on the second one. Instead, it doesnt do anything. Any help would be great. Thanks

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

0

querySelector returns the first element.

Instead, use querySelectorAll to select all elements, loop through each and add a click event listener:

const tick = document.querySelectorAll('.tic');

tick.forEach(e => {
  e.addEventListener('click', () => {
    var slot = e.id;
    console.log(slot);
  });
})
<div class="row">
  <div class="col-lg-12">
    <a class="btn btn-lg btn-primary tic" id="0">#</a>
    <a class="btn btn-lg btn-primary tic" id="1">#</a>
    <a class="btn btn-lg btn-primary tic" id="2">#</a>
  </div>
</div>

Or, even better, use event delegation:

document.body.addEventListener('click', function(e) {
  if (e.target.classList.contains("tic")) {
    console.log(e.target.id);
  }
})
<div class="row">
  <div class="col-lg-12">
    <a class="btn btn-lg btn-primary tic" id="0">#</a>
    <a class="btn btn-lg btn-primary tic" id="1">#</a>
    <a class="btn btn-lg btn-primary tic" id="2">#</a>
  </div>
</div>

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