addEventListener is throwing an error on the console of the chrome

Viewed 139

The HTML and JS is added below it is my challenge from my online tutor when I did it throws me an error But when she runs it runs well I will add the codes below please someone checks and let me know what is the mistake I made

var noofdrum = document.querySelectorAll(".drum").length;
for (i = 0; i < noofdrum; i++) {
  document.querySelector(".drum")[i].addEventListener("click", function() {
    alert("I got clicked");
  });
}
<h1 id="title">Drum  Kit</h1>
<div class="set">
  <button class="w drum">w</button>
  <button class="a drum">a</button>
  <button class="s drum">s</button>
  <button class="d drum">d</button>
  <button class="j drum">j</button>
  <button class="k drum">k</button>
  <button class="l drum">l</button>
</div>

The error is:

Uncaught TypeError: Cannot read property 'addEventListener' of undefined
1 Answers

You need to change to querySelectorAll inside the for loop.

Related