This would be one way of doing it...
document.querySelectorAll will get an array of elements (buttons) based on the class selector.
We then loop over this array using forEach - button is the current element we are iterating over while index is the index of that element in the array.
Finally, while looping, we attach a "click" event listener to each button and when that event is fired, we console.log the index from earlier.
const buttons = document.querySelectorAll('.buttonEl')
buttons.forEach(function(button, index){
button.addEventListener('click', function(){
console.log(index)
})
})
.action{
display: flex;
justify-content: space-around;
}
.buttonEl {
background-color: #CCC;
padding: 10px;
border-radius: 5px;
}
<div class="action">
<div class="buttonEl">Foo</div>
<div class="buttonEl">Bar</div>
<div class="buttonEl">Baz</div>
</div>