Jarla Jarla - 14 days ago 6
jQuery Question

How can I add a click function to an appended element?

I wonder why my

remove
button is not doing anything:



$(".click").click(function () {
$(".result").append("<tr class='element'><td>element</td><td><button type='button' class='remove'>remove</button></td></tr>");
});

$(".remove").click(function () {
alert("remove");
$(this).closest(".element").remove();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody class="result"></tbody>
</table>
<button class="click">add element</button>




Answer

You need to use delegation when you append elements dynamically.

Call the handler on the static parent/ancestor element, and then pass the element you want to delegate the click event to as the second parameter, like so:

$('.result').on('click', '.remove', function () {
  /* click handling here */
});