[jquery] remove table row with specific id

I have the following table:

<table id="test">
 <tr id=1><td>bla</td></tr>
 <tr id=2><td>bla</td></tr>
 <tr id=3><td>bla</td></tr>
 <tr id=4><td>bla</td></tr>
</table>

Now I want to remove row 3 from the table. How do I do that? Something like:

$("#test tr ??").remove();

Thanks!

This question is related to jquery

The answer is


Use the :eq selector:

$("#test tr:eq(2)").remove();

As bellow we can remove table rows with specific row id

<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
function remove(id)
{
$('table#test tr#'+id).remove();
// or you can use bellow line also
//$('#test tr#'+id).remove();
}
</script>
    </head>
<body>
<table id="test">
 <tr id="1"><td>bla</td><td><input type="button" onclick="remove(1)"value="Remove"></td></tr>
 <tr id="2"><td>bla</td><td><input type="button" onclick="remove(2)" value="Remove"></td></tr>
 <tr id="3"><td>bla</td><td><input type="button" onclick="remove(3)" value="Remove"></td></tr>
 <tr id="4"><td>bla</td><td><input type="button" onclick="remove(4)" value="Remove"></td></tr>
</table>
</body></html>

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

http://api.jquery.com/remove/


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

Might not work with numeric id's though.


Try:

$("#test tr:eq(2)").remove();

ID attributes cannot start with a number and they should be unique. In any case, you can use :eq() to select a specific row using a 0-based integer:

// Remove the third row
$("#test tr:eq(2)").remove();

Alternatively, rewrite your HTML so that it's valid:

<table id="test">
 <tr id=test1><td>bla</td></tr>
 <tr id=test2><td>bla</td></tr>
 <tr id=test3><td>bla</td></tr>
 <tr id=test4><td>bla</td></tr>
</table>

And remove it referencing just the id:

$("#test3").remove();

Simply $("#3").remove(); would be enough. But 3 isn't a good id (I think it's even illegal, as it starts with a digit).


Remove by id -

$("#3").remove();

Also I would suggest to use better naming, like row-1, row-2