view raw
Jarla Jarla - 6 months ago 41
jQuery Question

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

I wonder why my

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 () {

<script src=""></script>
<tbody class="result"></tbody>
<button class="click">add element</button>


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 */