Better Way to Remove Elements from a List?

I’m going to have a unordered list (<UL>) of items. Each item will have a delete button, which will make an ajax call & then remove the item from the list. I have all the info I need to make the Ajax call, but I’m wondering the best way to let the user remove any item in the list.

My first thought is to dynamically assign each <LI> a unique class identifier & then use jquery’s remove() on each element, but is there a better way? I have a feeling my approach is somewhat ham-fisted.

Asked on July 12, 2016 in No Category.
Add Comment
4 Answer(s)

No need to invent some unique class names (you meant unique identifiers, right? id, not class).

Just use the clicked button to find its parent li.

$('li .delete_button').click(function() {
  var that = this;
  $.post(url, data, function(data) {
    if(data.can_delete) {
Answered on July 12, 2016.
Add Comment


  <li>TEXT <input type="button" value="Delete" data-id="1" /></li>
  <li>TEXT <input type="button" value="Delete" data-id="2" /></li>
  <li>TEXT <input type="button" value="Delete" data-id="3" /></li>

And scripts

$("ul li input").click(function() {
  //ajax call on $(this).data('id');
Answered on July 12, 2016.
Add Comment

1, delete li elements which’s title are delete …

$("ul li").remove("li[title==delete]");

2, delete the second li element

var $li=$("ul li:eq(1)").remove(); 
Answered on July 12, 2016.
Add Comment

I don’t see anything wrong with your approach at all. Instead of using a class (which is slightly ham fisted) you could use dataset attributes, like <li data-unique-id="">, or even the id.

$("ul").on('click', 'li', function () {
   $.post('remove-script', 'id=' +, function () {
      $(this).fadeOut(function () { $(this).remove(); });
Answered on July 12, 2016.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.