for(var i = 1; i <= 3; i++) { var btn = document.getElementById('button'+i); btn.onclick = function() { alert('Hello from button ' + i); }; }