Want to add “addEventListener” on multiple elements with same class [duplicate]

You need to use querySelectorAll which will return a collection.Now use spread operator (three dots) to convert it to array and use forEach .Inside forEach callback add the event listener to it

[...document.querySelectorAll('.breakdown')].forEach(function(item) {
  item.addEventListener('click', function() {
    console.log(item.innerHTML);
  });
   });
<button id='btn-1' type="button" name="first" class="breakdown main-text"> Breakdown Start </button>
<button id='btn-2' type="button" name="second" class="breakdown main-text" disabled> Repair Start </button>
<button id='btn-3' type="button" name="third" class="breakdown main-text" disabled> Repair End </button>
<button id='btn-4' type="button" name="fourth" class="breakdown main-text" disabled> Breakdown Ended </button>

In your snippet you have also attached inline event handler,that may not be necessary.

If the objective is to enable the next button then a function to enable it can be called from the callback function of the event handler

Leave a Comment