2

I have a problem with my JQuery, I don't understand why the remove button don't work, could you help me please ? =) So here is my code :

$('.removeBook').on('click', function() {
  $('div').remove();
});

$('#createBook').click(function() {
  $('#list').append('<div>Hello' + '<button type="button" name="removeBook" class="removeBook">Remove</button>' + '</div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button type="button" name="createBook" id="createBook">Create</button>
<div id="list">
</div>

Thanks in advance if you can help me !

Uxrieg
  • 83
  • 6
  • The element with class `removeBook` only exists _after_ clicking on `button#createBook`. One possible solution would be to use [event delegation](https://learn.jquery.com/events/event-delegation/) – Andreas Mar 06 '17 at 10:52

1 Answers1

2

Your on function syntax is wrong. Since it is a dynamic element you should register the event on its container and to on function, Event should be first parameter and the second is selector.

And ("div").remove() removes all the div. You should change your code to

$("#list").on('click',"button.removeBook", function() {
  $(this).parent().remove();
});

Demo

Suresh Atta
  • 114,879
  • 36
  • 179
  • 284