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

domevent-handlingjavascriptjquery

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:

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