Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

84
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!