Alex Fariñas Alex Fariñas - 1 month ago 11
CSS Question

Remove li from ul with jquery from href

I want to remove all

<li>
row but instead I removing the tag
<a>
.
I just try
$(this).closest('li').remove()
but dont work also try
li.remove()
. I have this:

$("#demo").append("<li class='list-group-item'>" + result.Num+ " - " + result.Desc+ "<a onclick='$(this).remove()' href='#'class='pull-right'> Delete</a> </li>");

Answer

The correct method to solve your problem is to use $(this).closest('li').remove() to traverse to the nearest parent li to the clicked a and remove it. Note that you will need to escape the quotes within the string, which is the only reason I can see why what you tried would not work.

$("#demo").append('<li class="list-group-item">' + result.Num + ' - ' + result.Desc + '<a onclick="$(this).closest(\'li\').remove()" href="#" class="pull-right">Delete</a></li>');

However a much better approach is to use a delegated event handler instead of outdated on* event attributes, like this:

var $demo = $("#demo").append('<li class="list-group-item">' + result.Num + ' - ' + result.Desc + '<a href="#" class="pull-right">Delete</a></li>');
$demo.on('click', '.list-group-item a', function(e) {
    e.preventDefault();
    $(this).closest('li').remove();
});