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?
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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With