Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Remove LI from UL with a hyperlink in the LI

I have a unordered list:

<ul id="sortable">   <li id="1" class="ui-state-default">First <a href='#' title='delete' class="itemDelete">x</a></li>   <li id="2" class="ui-state-default">Second <a href='#' title='delete' class="itemDelete">x</a></li>   <li id="3" class="ui-state-default">Third <a href='#' title='delete' class="itemDelete">x</a></li> </ul> 

I want to remove the <li> from the <ul>. I have handled the click event of the class itemDelete where I try to do a remove but I assume its not working because I can't remove the <li> as a child is calling it?

$('.itemDelete').live("click", function() {             var id = $(this).parent().get(0).id;               $("#" + id).remove();          }); 

What's the best approach?

like image 532
Jon Avatar asked Jul 13 '09 14:07

Jon


People also ask

How to remove all <Li> tags from ul tag in HTML?

If there is no content in the UL tag. usually <ul> tag contains only <li> tags. If you want to remove all <li> tags then $ ("#ulelementID").html (""); will work. I think you need some thing else here. Please Sign up or sign in to vote. The content must be between 30 and 50000 characters. … Download, Vote, Comment, Publish. Forgot your password?

Is there a way to remove the Li elements from a list?

Of course there is a way to just remove the li elements too. With a for loop we can remove just remove the li elements. We use a different selector here to get all the li 's of the list instead of the list itself.

Should I remove the UL for a second search field?

I would recommend storing or caching the search field and the UL for the results in variables for easier interaction. Next question is you intent to replace the contents of the UL with the contents of the second search? If so there is no need to remove it just refactor how you add it.


2 Answers

Assuming you're using a recent version of jQuery:

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

closest is a little more dynamic than parent (although parent works here as well.) It gets the li that is closest to the current element, upwards in the structure.

like image 84
Blixt Avatar answered Sep 22 '22 17:09

Blixt


Actually, the way you have it as of now, id is going to be undefined, because none of the li's have ids.

why not just do

$(this).parent().remove() 

also, don't forget to return false.

like image 31
helloandre Avatar answered Sep 24 '22 17:09

helloandre