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.

6
  • Use $(".main ul").on("click", "li", function() ...); Commented Feb 12, 2015 at 2:26
  • See jsfiddle.net/mtg39cd5/1 Commented Feb 12, 2015 at 2: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. Commented Feb 12, 2015 at 2: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? Commented Feb 12, 2015 at 2:39
  • "click" doesnt work for delegated events. Using "on" allows you to pass a selector for event delegation: learn.jquery.com/events/event-delegation Commented Feb 12, 2015 at 2:41

1 Answer 1

1

Try to change

from

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

to

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

FIDDLE

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.