You can check if element has been clicked by attaching eventListener to it. For example:
element.addEventListener('click', myFunction);
This code willl fire "myFunction" every click on "element".
In your situation you have a list of elements. You want to determinate which element of the list has been just clicked.
One of the ways you can do it is:
- Select list of elements and assign it to variable (as you did)
- Convert this list to array
- Attach an eventListener to parent element of the list and using bubbling check which of the child element is clicked
- If one of the elements stored in array is clicked, fire the function (in the example below - logs to console index of clicked element in array)
It is not the best solution but I hope it shows the general concept of how to solve this problem. And here is the example implementation:
var parentElement = document.getElementById('parentElement')
var elements = document.getElementsByClassName('elements');
var elementsArr = Array.apply(null, elements);
parentElement.addEventListener('click', function(event) {
if (elementsArr.indexOf(event.target > -1)) {
console.log(elementsArr.indexOf(event.target));
}
}, true);
Helpful articles: