Add event handler to an element that not yet exists using on()?

javascript, jquery

Solution

$('body').on('click','p#two', function() {
    console.log('p#two clicked');
});

you can also use

$(document).on('click', 'p#two', function() {

});

Read more about `.on()`

you can also use `.delegate()`

$('body').delegate('#two', 'click', function() {

});

Problem

I want to add an event handle to an element that will be created later in DOM. Basically, what I am trying to do is that, when I click `p#one`, new element `p#two` will be created, then I click `p#two`, tell me "p#two" clicked. However, it doesn't work, I didn't get the `console.log` result of 'p#two clicked' after I click `p#two`. I use `on()` to add click event to `p#two`. What do I do wrong? Thanks. Below is my example code: ``` <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>on() test</title> <link type="text/css" href="http://localhost/jquery-ui-1.8.20.custom/css/smoothness/jquery-ui-1.8.20.custom.css" rel="stylesheet" /> <script type="text/javascript" src="http://localhost/jquery-ui-1.8.20.custom/js/jquery-1.7.2.min.js"></script> <script type="text/javascript" src="http://localhost/jquery-ui-1.8.20.custom/js/jquery-ui-1.8.20.custom.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $('p#two').on('click', function() { console.log('p#two clicked'); }); $('p#one').click(function() { console.log('p#one clicked'); $('<p id="two">two</p>').insertAfter('p#one'); }); }); // end doc ready </script> </head> <body> <p id="one">one</p> </body> </html> ```

Original source