I have got 3 buttons and I am trying to add their click behavior by pure Javascript dynamically, but seems an error is coming. Kindly, help:
<html>
<head></head>
<body>
<button id="btn-0">Button 1!</button>
<button id="btn-1">Button 2!</button>
<button id="btn-2">Button 3!</button>
<script type="text/javascript">
var prizes = ['A Unicorn!', 'A Hug!', 'Fresh Laundry!'];
for (var i = 0; i < prizes.length; i++) {
// for each of our buttons, when the user clicks it...
document.getElementById('btn-' + (i-1)).onclick = function() {
alert(prizes[i-1]);
};
}
</script>
</body>
</html>
Please, help me understand how to dynamically bind events with 'getElementById'.