I'm creating a small project where there are many buttons with the same class calling the same function. I've pushed them into an array using a loop. Now, depending on the button the user presses, it should call said function, and also pass an unique parameter based on its array index.
So basically, I want to create a loop that gives all the same-classed buttons an eventListener to call the function, but with a different parameter. This is what i've tried:
let CTAs = []
for(i = 0; i < document.getElementsByClassName("CTAenabled").length; i++) {
CTAs.push(document.getElementsByClassName("CTAenabled")[i])
CTAs[i].addEventListener("click", () => {myFunction(i)})
}
function myFunction(n) {
console.log(n)
}
Using this loop, all buttons are properly pushed into the array, but when pressed, they all pass the same parameter, making the function print the same number.
Any ideas on how to give each button a different parameter according to its index?