0

I have 4 buttons in HTML:

      <button id="option_one" class="question_option">Option 1</button>
      <button id="option_two" class="question_option">Option 2</button>
      <button id="option_three" class="question_option">Option 3</button>
      <button id="option_four" class="question_option">Option 4</button>

In JS I would like to add an event listener to the question_option class and manipulate only the button that was clicked, instead of adding an event listener for every button. On click the button will change style and change a variable's value.

Wild-tuna
  • 3
  • 3
  • You have 2 options: 1. event delegation; 2. adding event to each element – Konrad Aug 15 '22 at 08:54
  • When you hook up an event handler to an element via `addEventListener`, during the call to the handler, you can access the element for that specific event via `this` or the `currentTarget` property of the `event` object your handler receives. Or if you use event delegation, you can find the relevant element by starting from `event.target` and possibly using [`closest`](https://developer.mozilla.org/en-US/docs/Web/API/Element/closest) to find the element -- with what you have, `event.target` would be the `button`, but if you put child elements in the `button`s, you'd have to use `closest`. – T.J. Crowder Aug 15 '22 at 09:04
  • [`addEventListener` on MDN](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) – T.J. Crowder Aug 15 '22 at 09:07

0 Answers0