Remove dynamically generated <div> on click

event-delegation, javascript, jquery

Solution

$("#containerr").on('click', '.remove', function(){
  $(this).closest('.helpcont').remove();
});

`#containerr` = the closest parent that is not added dynamically

`click` = event (you can add multiple events by separating them with spaces)

`.remove` = the selector on which to trigger the event

PS: Use selectors like `#id` instead of `element#id`. IDs should be unique anyway, so there's no need to do it the slow way, by making jQuery retrieve all DIV elements, and then searching for the one with the given ID.

Problem

I am trying to a `<div>` when it is clicked. When I tried with `.live()` it shows me: object has no method live() I am using jQuery version 1.9, so `live` has been removed. ``` $(document).ready(function(){ $('#addhelper').click(function(){ $('div#containerr').append('<div class ="helpcont"><input type="text" name="helper_caption[]" class="input-large" placeholder="Caption">'+ '<input type="text" name="helper_url" class="input-large" placeholder="Url">'+ '<input type="text" name = "helper_source" class="input-large" placeholder="Source"><button class = "remove" type="button">remove</button></div>'); }); $("button.remove").on({ click: function(){ $(this).remove('div.helpcont'); } }); }); ```

Original source