I have a list with one preexisting button that deletes itself when it’s clicked. When the add button is clicked, another button is added to the list, but this time, the appended button does not delete itself even though it is of the same class.
http://jsfiddle.net/PEh6H/
Here’s some sample code because I have to include it:
$(function() {
$("#add").on('click', addListItem);
$(".delete").on('click', deleteItem);
});
function deleteItem(){
$(this).parent().remove();
}
function addListItem(){
$("#todolist").append('<li><button class="delete">This one doesn\'t</button></li>');
}
And the html:
<ul id="todolist">
<li><button class="delete">This one works</button></li>
</ul>
<button id="add">Add</button>
You should delegate the event, from one of static parents of the element or document object.
http://jsfiddle.net/5RkHd/