+ 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?
1 Answer
+ 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);