need help getting values from a click function in javascript

Viewed 21

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

1 Answers

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>

Related