0

I'm trying to add an event listener to dynamically created elements, but am having trouble doing so. In my code below, I can never detect that <p> has been inserted so I never see the console message Bar Inserted. Am I doing somethign incorrectly?

http://jsfiddle.net/3msVK/

    $('#button').click( function() {
        $('#foo').append('<p>foo</p>');
        $('p').append('<p>bar</p>');
    });  
    $('#foo').bind('DOMNodeInserted', function() {
        console.log('Foo Inserted');
    });  
    $('p').on('DOMNodeInserted', 'p', function() {
        console.log('Bar Inserted');
    });    

    <div id="foo">Foo</div>
    <div id="button">BUTTON</div>

1 Answer 1

1

When you first attach the listeners, $('p') doesn't select anything (since there isn't a p on the page yet). You should attach the listener to the parent, #foo:

$('#button').click( function() {
    $('#foo').append('<p>foo</p>');
    $('p').append('<p>bar</p>');
});  
$('#foo').bind('DOMNodeInserted', function() {
    console.log('Foo Inserted');
});  
$('#foo').on('DOMNodeInserted', 'p', function() {
    console.log('Bar Inserted');
});    

<div id="foo">Foo</div>
<div id="button">BUTTON</div>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.