0

My problem is rather hard to word. So I have created a jsfiddle.net of my issue.

I have a list of divs. Inside each div there is some text and an "X". The "X" is to delete the parent div. The three divs and "X" works fine. But if I were to add a button that appends a new div to the list, then those "X"'s don't work. Any idea what this problem is? I know this is probably some basic JS DOM thing. But I'm self thought and just don't understand JS very well to resolve this issue.

Please and thank you for your time.

http://jsfiddle.net/JLxKJ/

$("#trigger").click(function() {
    $("#participants_wrapper").append("<div class='participant'><a href='javascript:void(0)' class='delete_participant'>X</a>Appended</div>");
    return false;
});
$(".delete_participant").click(function(){
    $(this).closest('div').remove();
});
<div id="participants_wrapper">
  <div class="participant"><a href="javascript:void(0)" class="delete_participant">X</a>already here</div>
  <div class="participant"><a href="javascript:void(0)" class="delete_participant">X</a>already here</div>
  <div class="participant"><a href="javascript:void(0)" class="delete_participant">X</a>already here</div>
</div>
<a href="javascript:void(0)" id="trigger">add this participant</a>
CS Studios
  • 25
  • 4

3 Answers3

2

You need to delegate the event to closest existing parent in the dom:

$("#participants_wrapper").on("click", ".delete_participant", function(){
    $(this).closest('div').remove();
});

This is because jQuery can't put the click event on the element, as it doesn't exist on page load, so this puts the event on the parent, but affects the children

Andy
  • 13,875
  • 3
  • 46
  • 76
Jai
  • 71,335
  • 12
  • 70
  • 93
0

because you are not binding the events again to the new element.

You can use on() to get around that.

$("#participants_wrapper").on("click", ".delete_participant", 
    function(){
        $(this).closest('div').remove();
    }
);
epascarello
  • 185,306
  • 18
  • 175
  • 214
0

For dynamically added elements, use jQuery's .on() function. Change your delete code to:

$("#participants_wrapper").on('click', '.delete_participant', function () {
    $(this).closest('div').remove();
});

jsFiddle example

j08691
  • 190,436
  • 28
  • 232
  • 252