Adding event handler to newly created element
dom, jquery
Solution
Wrap up the new element in jQuery tags and apply the event handler at that time. This is a cleaner and more efficient approach than using somewhat complicated jQuery selectors to assign the event handler after the element has already been inserted into the DOM:
//this line will create your element in memory, but not insert it to the DOM
var newElmt = $('<li>' + label + ' <a href="#remove_'+id+'">[remove]</a></li>');
//you can apply jQuery style event handlers at this point
newElmt.on('click',function(e) {
alert('Removing: '+$(this).attr('href').substr(8));
event.preventDefault();
});
//insert the element as you were before
$('#list ol').append(newElmt);
Problem
I'm trying to add new element to ordered list with link for it's removal: ``` $('#list ol').append('<li>' + label + ' <a href="#remove_'+id+'">[remove]</a></li>'); ``` but this is not working: ``` $('a[href^="#remove"]').on('click', function(event){ alert('Removing: '+$(this).attr('href').substr(8)); event.preventDefault(); }); ``` Any idea why?