Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing specific element from a list with JQuery

Tags:

jquery

list

i have a dynamic list, which looks like this:

<ul>
<li class="border" id="tl_1">Text1</li>
<li class="border" id="tl_2">Text2</li>
<li class="border" id="tl_3">Text3</li>
</ul>

The list can have more items than these three.

When someone clicks on a specific button, i want that e.g. the "tl_2" will be removed from the list. I tried it whith these JQuery commands, but non of them were working:

$('#tl_2').remove();

or

$('li').find('tl_1').remove();

How can i solve this?

like image 953
Torben Avatar asked Feb 12 '12 13:02

Torben


People also ask

How remove Li tag in jQuery?

If you want to remove all <li> tags then $("#ulelementID"). html(""); will work.

Why remove function is not working in jQuery?

Your clear() function is not global because it is defined inside your document ready handler, so your onclick="clear()" can't find it. You need to either move the function outside the ready handler (making it global), or, better, bind the click with jQuery: $(document). ready(function(){ $(this).


1 Answers

You probably have more than one element with the same ID.

You don't have to use ID at all in case you want to remove them by index you can use the .eq() method:

$("#btnRemove").click(function() {
    $("#myList li").eq(1).remove();
});

This will remove the second list item each click.

Live test case.

like image 122
Shadow Wizard Hates Omicron Avatar answered Nov 06 '22 05:11

Shadow Wizard Hates Omicron