Javascript – How to attach event handlers to dynamically-generated DOM elements using jQuery


I have a <ul> tag that I want to append some <li> tags inside. Example:

$('body').append("<ul id='myUL'>").find("ul");
$('#myUL').append('<li id='a'>a</li>');
$('#myUL').append('<li id='b'>b</li>');

I want to give every <li> a different click event. How can I accomplish that?

Best Solution

Try something like this:

    .attr('id', 'myUL')
        $('<li>a</li>').click(function() {
            alert('First one clicked');
        $('<li>b</li>').click(function() {
            alert('Second one clicked');