How to get the index of an element in a HTML collection when that element is clicked, using javascript
05:59 10 Jan 2021

I have five buttons in my HTML file.

Seeing as they are five, I would like to be able to print the index of the specific button that has been clicked in the HTML collection. i.e on tapping btn 4 I should see 3 printed. I tried putting together some javascript lines that I thought would do it but in vain. The JS code is:

if (document.readyState == 'loading') {
        document.addEventListener('DOMContentLoaded',execute);
    }else{
        execute()
    }
    function execute() {
        var btns = document.getElementsByClassName('item');
        for (var i = 0; i < btns.length; i++) {
            btns[i].addEventListener('click',btnClicked);
        }       
    }
    function btnClicked(event,btns) {
        var btn = event.currentTarget;
        var btnIndex = btns.indexOf(btn)
        console.log(btnIndex)
    }

        

What is the way to go?

javascript html arrays dom dom-events