I have just been experimenting with JavaScript and was trying this code.
var elements = document.getElementsByTagName("p");
var n = elements.length; // Should be: 10
for (var i = 0; i < n; i++) {
elements[i].onclick = function () {
console.log("This is element #" + i);
};
}
<p>Element: #1</p>
<p>Element: #2</p>
<p>Element: #3</p>
<p>Element: #4</p>
<p>Element: #5</p>
However, when the code is run, something weird occurs. Basically, for example, if you click on element #1, it will say that you've clicked on element #5.
This is what I am curious to know:
- Why is this occurring?
- Is there a fix for it?