skip to Main Content

I have a list of buttons and each time one has been clicked I want to check if the one that has been clicked has a certain class name. I have looped over the button and then said if the button contains a class but this doesn’t work.

2

Answers


  1. You need to add an event listener to the buttons to listen for the "click" event.

    const helpBtn = document.querySelectorAll('.helpBtn');
    
    for (let h = 0; h < helpBtn.length; h++) {
      helpBtn[h].addEventListener('click', () => {
        if (helpBtn[h].classList.contains('doesHelp')) {
          console.log('Helped')
        }
      });
    }
    <button class="helpBtn doesHelp">Help</button>
    <button class="helpBtn">Help</button>
    <button class="helpBtn doesHelp">Help</button>
    Login or Signup to reply.
  2. The problem was that you wrote helpBtn[i] instead of helpBtn[h]:

    helpBtn[i].addEventListener('click', () => {
    

    and i doesn’t exist.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search