I have five buttons with the same class name. I have an onclick function that should console.log the index of the clicked button | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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
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);
4th May 2021, 8:52 PM
Valen.H. ~
Valen.H. ~ - avatar