Using addEventListener and getElementsByClassName to pass an element id
You can get the id from the element that responded to the click event with this.id
:
var items = document.getElementsByClassName('menu');
for (var i = 0; i < items.length; i++) {
items[i].addEventListener('click', printDetails);
}
function printDetails(e) {
console.log("Clicked " + this.id);
}
<ul>
<li class="menu" id="bob">Robert Smith</li>
<li class="menu" id="jane">Jane Doe</li>
<li class="menu" id="sue">Susan Carter</li>
</ul>
codepen demo
var userSelection = document.getElementsByClassName('menu');
for(var i = 0; i < userSelection.length; i++) {
(function(index) {
userSelection[index].addEventListener("click", function() {
console.log("Clicked index: " + index);
})
})(i);
}
As pointed out by @torazaburo in the comments, you can use the following if the browsers you want to support are complying with ECMAScript 6 (ES6), the newest version of JavaScript.
var userSelection = document.getElementsByClassName('menu');
for(let i = 0; i < userSelection.length; i++) {
userSelection[i].addEventListener("click", function() {
console.log("Clicked index: " + i);
})
}