I have several elements that get eventlisteners added so I can capture event data. It works great but I need each to have a unique ID. If you look at the snippet below, you can see that the ID will always last value.
var buttons = document.getElementsByClassName('class');
for (var i = 0; i < buttons.length; i++) {
var id = i + 1;
buttons[i].onclick = function() {
buttonClicked(id);
}
}
function buttonClicked(id) {
document.getElementById('output').innerHTML = 'Button ID: ' + id;
}
<button class="class">Button 1</button>
<button class="class">Button 2</button>
<hr>
<div id="output"></div>
I am aware that you could put the onclick event in the HTML, but I need the event data. It also needs to have the onclick in as a function()
as I have it. Is there a way I could somehow freeze the id
variable value for the function?