Check out this HTML code snippet
<body>
<div>
<button>
Button A
</button>
<button>
Button B
</button>
<button>
Button C
</button>
</div>
</body>
This is my attempt at coding:
(function () {
var buttonArray = document.getElementsByTagName("button");
for (var j = 0, length = buttonArray.length; j < length ;j++) {
buttonArray[j].onclick = function() {
alert(j)};
}
}())
After clicking on each button, why does each one return the value of 3? Shouldn't they show different values?