-2

I'm sure this has been asked before.

Basically, I'm creating an RPG calculator - what I wanted to know is if there is a way for me to assign an ID to certain button elements in HTML and check if they are clicked. The reason for this is so that I can keep everything under a single function, rather than spanning it over multiple functions like I would have done a year ago.

Any way for me to do such a thing?

Kashiki
  • 19
  • 1
  • 6

1 Answers1

-1
<div>
  <button class="btn">Button 1</button>
  <button class="btn">Button 2</button>
</div>

<script>
  var els = document.getElementsByClassName('btn');
  for (var i = 0; i < els.length; i++) {
    els[i].id=i;
    els[i].addEventListener('click', function () { console.log(this); });
  }
 </script>
Mark S
  • 839
  • 6
  • 11