Search code examples
jqueryxhtmlclosest

jquery closest() selecting


I am having issues getting my remove element function working.

I have this function:

//Remove an Item From Any Group
function deleteItem (selector) {
  $(selector).closest("li").fadeOut(500, function() { 
    $(selector).closest("li").remove();
  });
}

Then this to call it,

$("a.delete").live('click', function() {
  deleteItem("li span.delete a.delete");
});

With this HTML:

<ul>
  <li><img src="" width="40" height="40" class="image"/><span><a href="#">Drinkers Pub</a></span><span class="delete"><a href="javascript:;" class="delete">delete</a></span></li>
  <li><img src="" width="40" height="40" class="image"/><span><a href="#">Drinkers Pub</a></span><span class="delete"><a href="javascript:;" class="delete">delete</a></span></li>
  <li><img src="" width="40" height="40" class="image"/><span><a href="#">Drinkers Pub</a></span><span class="delete"><a href="javascript:;" class="delete">delete</a></span></li>
</ul> 

The problem is it is only removing the first LI in the list no matter which link. I thought closest picks the closest element from the event. IN this case the click of the delete button.

What am I missing?


Solution

  • You are passing the deleteItem function a selector that gets you all of the delete links. You'll want something more like this.

    function deleteItem (link) {
      link.closest("li").fadeOut(500, function() { 
        link.closest("li").remove();
      });
    }
    
    $("a.delete").live('click', function() {
      deleteItem($(this));
    });