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)
}
<body>
<div class="btn-items">
<button class="item">btn 1 </button>
<button class="item">btn 2 </button>
<button class="item">btn 3</button>
<button class="item">btn 4</button>
<button class="item">btn 5</button>
</div>
</body>
What is the way to go?