2

What I am trying to do is get the id name of newly added item in the list on click. Here's my code.

$(document).ready(function() {

  $('ul>li').on('click', function() {
    var idName = $(this).attr('id');
    alert(idName);
  });

  $('#add').click(function() {
    var n = Math.floor((Math.random() * 100) + 1);
    $('ul').prepend('<li id="name-' + n + '">New Item</li>');
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul>
  <li id="name-88">Old Item</li>
  <li id="name-59">Old Item</li>
  <li id="name-48">Old Item</li>
</ul>
<button id="add">Add Item</button>

JSFiddle

Vianne
  • 548
  • 1
  • 10
  • 31

4 Answers4

2

You need to use $(document).on('click', 'ul>li', function(){}); instead of $('ul>li').on('click', function() { }); this is because you are adding the element dynamically after the jquery code is loaded. Thus, $('ul>li').on('click', function() { }); will not detect click event on the newly added element. To overcome this, you need to assign the click event to ul>li at document level so whenever a new element is added it is in the context of document and listens for the click event on ul>li

$(document).ready(function() {

  $(document).on('click', 'ul>li', function() {  
    var idName = $(this).attr('id');
    alert(idName);
  });

  $('#add').click(function() {
    var n = Math.floor((Math.random() * 100) + 1);
    $('ul').prepend('<li id="name-' + n + '">New Item</li>');
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li id="name-__">New Item</li>
  <li id="name-88">Old Item</li>
  <li id="name-59">Old Item</li>
  <li id="name-48">Old Item</li>
</ul>
<button id="add">Add Item</button>
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
0

To get the id of a newly created item, use ele:first CSS property. call it on click method.

let new_el_id = $("ul").find("li:first").attr("id");
BugHunter
  • 1,194
  • 2
  • 9
  • 15
0

Update your listener each time new item added, Try

$(document).ready(function() {
  addListener();

  function addListener() {
    $('ul li').on('click', function() {
      var idName = $(this).attr('id');
      alert(idName);
    });
  }

  $('#add').click(function() {
    var n = Math.floor((Math.random() * 100) + 1);
    $('ul').prepend('<li id="name-' + n + '">New Item</li>');
    addListener();
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul>
  //
  <li id="name-__">New Item</li>
  <li id="name-88">Old Item</li>
  <li id="name-59">Old Item</li>
  <li id="name-48">Old Item</li>
</ul>
<button id="add">Add Item</button>
Saeed
  • 5,413
  • 3
  • 26
  • 40
0

try this

$('ul').on('click','li', function() {  
    var idName = $(this).attr('id');
    alert(idName);
});
user3551009
  • 174
  • 6