How to reference dynamically created elements with jQuery

If your HTML looks like:

<body>
<div id="my-div">
</div>
</body>

And you add an element dynamically through jQuery:

$('#my-div').append('<button id="my-button">My Button</button>');

To add a click function to the button, do:

$('#my-div').on('click', '#my-button', function () {

alert('Hello World!');
});

JSFiddle: https://jsfiddle.net/wwgfcg1u/3/

Creator of Goalsmash.net. Help others achieve their goals. Get paid.

Creator of Goalsmash.net. Help others achieve their goals. Get paid.