Why doesn't the code below print it's corresponding value when clicked?
Instead, it prints 5?
var recipeDiv = document.createElement("div");
var recipeUL = document.createElement("ul");
for (var i = 0; i < 5; ++i) {
var listNode = document.createElement("li");
listNode.innerHTML = i;
listNode.onclick = function() { alert(i); }
recipeUL.appendChild(listNode);
}
recipeDiv.appendChild(recipeUL);
addNodeToDOM(document.body, recipeDiv, 'recipe');
function addNodeToDOM(element, node, id) {
var div = document.createElement('div');
div.id = id;
div.appendChild(node);
element.appendChild(div);
}
I was able to reproduce the bug here: jsfiddle
But basically, I'm not sure if this is the convention for adding elements correctly to the DOM. If so, how come whenever I click on the list elements, it doesn't show