I have a div, where I set the innerHTML after a button has been clicked:
$('#headerDiv').html('Welcome [<a href=\'javascript:void(0);\' id=\'logout_button\'>Logout</a>]');
However, the new element logout_button isn't registered in the DOM, so I can't capture click events using the traditional $('#logout_button').click().
Is it possible to register logout_button in the DOM just after it's been set with the html() method?
Thanks!
To add a new element to the HTML DOM, you must create the element (element node) first, and then append it to an existing element.
Answer: Use the jQuery append() or prepend() method You can add or insert elements to DOM using the jQuery append() or prepend() methods. The jQuery append() method insert content to end of matched elements, whereas the prepend() method insert content to the beginning of matched elements.
The jQuery prepend() method inserts content AT THE BEGINNING of the selected HTML elements.
Delegate the event
$('#headerDiv').on('click', '#logout_button', function() {
// Your code
});
This will make sure the event is attached to the dynamically added element by the concept of event bubbling.
If delegation isn't your cup of tea, you can bind your click handler to the button before attaching the button. Do that by creating DOM elements and appending them:
var btn = $('<a />').text('Logout').attr({
"href": "javascript:void(0);",
"id": "logout_button"
}).click(function (e) {
// do logout stuff
e.preventDefault();
return false;
});
$('#headerDiv').append(btn);
This has the added bonus of ensuring you are adding valid elements to the DOM.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With