What I'm trying to do is to add elements, with some text written on them, and when I click them I want that text to be shown as alert
.
(arr
is an array of strings)
for (var i=0; i<arr.length; i++) {
var node = document.createElement("p");
var textNode = document.createTextNode(arr[i]);
node.appendChild(textNode);
//Add click event listener
node.addEventListener("click", function () {
alert(arr[i]);
});
//add node to list div section
document.getElementById("list").appendChild(node);
}
}
This doesn't work correctly.
All nodes are responding to click by alert param undefined
.
I understand its because arr
doesn't exist anymore when function is invoked.
How do I fix this?