I know im doing something really really stupid here.Im getting the error document.getElementById() is null or not an object. Could some one please help me with this?
<body>
<div id="box1" style="width:100px;height:100px;background:#ccc;"></div>
<div id="box2" style="width:100px;height:100px;background:#ccc;"></div>
<div id="box3" style="width:100px;height:100px;background:#ccc;"></div>
<div id="box4" style="width:100px;height:100px;background:#ccc;"></div>
<div id="box5" style="width:100px;height:100px;background:#ccc;"></div>
<script>
for (var i = 0; i < 5; i++) {
document.getElementById('box' + i).onclick = function() {alert('You clicked on box #' + i);};
}
</script>
</body>
Thank You
Indexing Issue
iis starting on0. There is no box calledbox0. Change loop to:Scope Issue
As pointed out by commentators, there is also a scope issue with the code. Change it to: