I am trying to made a series of buttons (in the div included in the html) give an alert when clicked. For that I am using addEventListener. If I just make a list (as showed belowed commented) the result is fine. I try to make the code DRY by using a for loop but it returns me only that "clicked 8" no matter what I press. As far as I understand the flow should start by testing i=0 and continue with the others the same way as with the entire list. So if I press the button[0] I should get "clicked 1" and that's all because the other conditions are false. Thanks in advance.
// document.querySelectorAll("button")[0].addEventListener("click", function(){alert("clicked 1")});
// document.querySelectorAll("button")[1].addEventListener("click", function(){alert("clicked 2")});
// document.querySelectorAll("button")[2].addEventListener("click", function(){alert("clicked 3")});
// document.querySelectorAll("button")[3].addEventListener("click", function(){alert("clicked 4")});
// document.querySelectorAll("button")[4].addEventListener("click", function(){alert("clicked 5")});
// document.querySelectorAll("button")[5].addEventListener("click", function(){alert("clicked 6")});
// document.querySelectorAll("button")[6].addEventListener("click", function(){alert("clicked 7")});
for(i=0; i<=6; i++) {
document.querySelectorAll("button")[i].addEventListener("click", function(){alert("clicked " + (i+1))});
}
<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>