2

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
Ivar
  • 6,138
  • 12
  • 49
  • 61
Kavin
  • 21
  • 1
  • `document.querySelector()` only returns a single element, so you can't use `[i]` on it. Store the element collection from `document.querySelectorAll(".drum")` into a variable and loop over those elements instead. – Ivar Feb 14 '21 at 12:39

1 Answers1

1

You need to change to querySelectorAll inside the for loop.