1

I have this JavaScript code that prints a list of names. Every list item has a "data-age" attribute with the age of the person. When you click on a name, it is supposed to print their age in the console, however, it always says undefined.

Is it not possible to get the data from dynamically added elements?

$(() => {

  var data = [{
      name: "John",
      age: 23
    },
    {
      name: "Simon",
      age: 16
    },
    {
      name: "David",
      age: 43
    }
  ];

  for (var i = 0; i < data.length; i++) {
    $("ul").append("<li data-age=" + data[i].age + ">" + data[i].name + "</li>");
  }

  $("li").click(() => {
    console.log($(this).data("age"));
  });

});
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<ul></ul>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Reimar
  • 11
  • 1
  • 1

0 Answers0