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
jQuery Events
jQuery Mouse, Keyboard and Form Events
jQuery Event Delegation
Exercises & Assignments
Write jQuery code to hide a paragraph when a button is clicked
Write jQuery code to highlight the clicked list item
Write jQuery code to remove a list item when it is clicked
Write jQuery code to change the image source when a thumbnail is clicked
Write jQuery code to show the text typed in an input field
Write jQuery code to filter a list while typing in a search box
Write jQuery code to count the clicks of a button
Interview Questions & Answers
What is the on() method in jQuery?
What is the difference between click() and on(‘click’) in jQuery?
What is event bubbling in jQuery and how do you stop it?
What is event.preventDefault() in jQuery?
What is event delegation in jQuery and why is it useful?
What is the difference between bind(), live(), delegate() and on() in jQuery?