Write jQuery code to remove a list item when it is clicked

Description: Clicking on the “Delete” button of an item must remove that item. It must also work for the new items.

Hint:

  • Use a delegated event on the list and .closest('li').remove().

HTML of the page

<ul id="list">
  <li>Item 1 <button class="del">Delete</button></li>
  <li>Item 2 <button class="del">Delete</button></li>
</ul>

Solution

$('#list').on('click', '.del', function () {
  $(this).closest('li').remove();
});

// a new item added later
$('#list').append('<li>Item 3 <button class="del">Delete</button></li>');

$('.del').eq(0).click();    // delete the first
$('.del').eq(1).click();    // delete what is now the second (the new one)
console.log('items left: ' + $('#list li').length);
Console output

items left: 1

HTML after the code runs

<ul id="list">
<li>
Item 2
<button class="del">Delete</button>
</li>
</ul>

How it works

  • The handler is on the list, so it also works for the items which are added later.
  • closest('li') finds the item of the clicked button.

Read Event Delegation and Remove Elements.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.