0

Case1: List is present in the html already

<ul id="list1">
    <li>One</li>
    <li>Two</li>
</ul>

The clicked li element is detected using

$('#list1 li').bind('click', function(){
   alert($(this).html());
});

Above works fine.

Case 2:

Now if the list is added dyamically

<div id="testDiv">
</div>

var output = '<ul id="list1">' +
             '<li>One</li>' + 
             '<li>Two</li>' +
             '</ul>';

$('#testDiv').html(output);

I try to detect the clicked li element using same code

$('#list1 li').bind('click', function(){
    alert($(this).html());
});

In this case, it does not detect

user544079
  • 15,221
  • 39
  • 109
  • 166

1 Answers1

3

In that case use event delegation

$('#testDiv').on('click', '#list1 li', function () {
    alert($(this).html());
});
Arun P Johny
  • 376,738
  • 64
  • 519
  • 520