1

I'm trying get the ID of appended list element. After trying out for hours and reading multiple sources from jquery get the id/value of LI after click function and How to get the id of html list item using jquery?, I still couldn't figure it out the bug inside my code.

The only difference between the above sources and what I'm trying to achieve is they already have list element present inside html where as I'm appending list through jquery function.

Here is my code.

Html

<button id="display">Display</button>
<div class="main">
    <ul>
    </ul>
</div>
<p id="show"> </p>

Jquery 2.1.0

var i = 1;
$('#display').click(function() { 
   $(".main ul").append(
       $('<li>').attr("id",i).append(
           $('<p>').append("Stackoverflow")
           ));
    i++;
});


$('.main ul li').click(function () { 
    $('#show').text("List ID =" + this.id);       
});

jsfiddle

Thank you for your time.

Community
  • 1
  • 1
Ray.Rai
  • 43
  • 6
  • Use `$(".main ul").on("click", "li", function() ...);` – Barmar Feb 12 '15 at 02:26
  • See http://jsfiddle.net/mtg39cd5/1/ – Barmar Feb 12 '15 at 02:26
  • Thanks for quick reply Barmar it's working now, I'll check documentation on on(), but could you shortly explain why click didn't worked but .on did. – Ray.Rai Feb 12 '15 at 02:36
  • Because the selector only returns the elements that exist at the time that it's called, which is when the page is loaded, and then you give them click handlers. How can that have any effect on elements that don't exist yet? – Barmar Feb 12 '15 at 02:39
  • "click" doesnt work for delegated events. Using "on" allows you to pass a selector for event delegation: http://learn.jquery.com/events/event-delegation/ – ChrisJ Feb 12 '15 at 02:41
  • Again thanks Barmar, you short explain really helped. – Ray.Rai Feb 12 '15 at 22:49

1 Answers1

1

Try to change

from

$('.main ul li').click(function () { 

to

$('.main').on('click', 'ul li', function () { 

FIDDLE

Lumi Lu
  • 3,289
  • 1
  • 11
  • 21