+ 1

I have five buttons with the same class name. I have an onclick function that should console.log the index of the clicked button

The onclick eventlistener is in the javascript. Not in the DOM. Like this: ( btn=document.querySelectorAll('.btn'); btn.addeventlistener('click', showindex);. How do I create a function that identifies the index of the button that has been clicked?

4th May 2021, 8:38 PM
Austin King'ori
Austin King'ori - avatar
2 Réponses
+ 7
querySelectorAll returns a NodeList, so you have to iterate it and assign a listener to btn[i].addEventListener.... Then, this event listener you pass has an event object as first parameter. item.onclick = e => console.log("i am:", e.target);
4th May 2021, 8:52 PM
Valen.H. ~
Valen.H. ~ - avatar