0

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?

brkeyal
  • 1,317
  • 1
  • 16
  • 22

1 Answers1

0

You've tagged this with jQuery, so here's a jQuery solution; use a delegated event on the parent element which the created ones are appended to. Try this:

$('#list').on('click', 'p', (function() {
    alert($(this).text());
});

for (var i = 0; i < arr.length; i++) {
    $('<p />', { text: arr[i] }).appendTo('#list');
}
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339