Iccarys
Iccarys

Reputation: 31

remove() not working when trying to remove <li> generated from a button

I have a button that adds li to the ordered list. Within this item added, there is a delete button. I'm trying to have this button nested within the li delete itself and parent but remove() does not seem to work.

$('.add').click(()=>{
  var item = "<li>Item - <button class='delete'>Delete</button></li>"
  
  $('ol').append(item);
  
});

$('ol').on( 'click','.delete' ,(e)=>{
  console.log('clicked');
  
  $(e).parent().remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ol>

</ol>
<button class='add'>Add</button>

Upvotes: 2

Views: 34

Answers (2)

cmac
cmac

Reputation: 3268

This will do it:

$('ol').on('click', '.delete', function () {
  console.log('clicked');
  $(this).parent().remove();
});

Upvotes: 0

Use $(e.target).parent().remove();, since e.target tells what element was clicked.

The reason your add function works, it because you don't have to interact with the element you click on.

Demo

$('.add').click(()=>{
  var item = "<li>Item - <button class='delete'>Delete</button></li>"
  
  $('ol').append(item);
  
});

$('ol').on( 'click','.delete' ,(e)=>{
  
  $(e.target).parent().remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ol>

</ol>
<button class='add'>Add</button>

Upvotes: 3

Related Questions