Reputation: 11377
I have an HTML table with one TH row and several TRs that are added dynamically. Each TR has a button in the last column.
What do I need so that by click on the button the closest TR gets removed from the table?
I tried using $(this).closest.remove()
but this didn't work so I assume I need to add IDs or something else here.
A basic example table would look like the following:
<table class='tableClass'>
<tbody>
<th>
<td>Text</td><td>Text</td><td>Text</td>
</th>
<tr>
<td>Text</td><td>Text</td><td><button type='button' class='btnClass'>Delete</button></td>
</tr>
<tr>
<td>Text</td><td>Text</td><td><button type='button' class='btnClass'>Delete</button></td>
</tr>
<tr>
<td>Text</td><td>Text</td><td><button type='button' class='btnClass'>Delete</button></td>
</tr>
</tbody>
</table>
Upvotes: 1
Views: 1916
Reputation: 1299
From your HTML code it looks like you want to remove parent TR, try this
$(".btnClass").click(function(){
$(this).parents("tr:first").remove();
});
Upvotes: 1
Reputation: 1292
$(".btnClass").click(function(){
$(this).parents('tr').remove();
});
Upvotes: 1
Reputation: 73916
You can do this using .closest( selector )
properly like:
$(this).closest('tr').remove();
Actually in your code:
$(this).closest.remove()
___^___
you are missing both the opening and closing parenthesis ()
and the selector tr
.
Upvotes: 1
Reputation: 337620
You need to give the closest
function a selector. Try this:
$('.btnClass').click(function() {
$(this).closest('tr').remove();
});
Also, your HTML is invalid as th
should be a child of tr
:
<table class='tableClass'>
<tbody>
<tr>
<th>Text</th>
<th>Text</th>
<th>Text</th>
</tr>
<tr>
<td>Text</td>
<td>Text</td>
<td>
<button type='button' class='btnClass'>Delete</button>
</td>
</tr>
<tr>
<td>Text</td>
<td>Text</td>
<td>
<button type='button' class='btnClass'>Delete</button>
</td>
</tr>
<tr>
<td>Text</td>
<td>Text</td>
<td>
<button type='button' class='btnClass'>Delete</button>
</td>
</tr>
</tbody>
</table>
Upvotes: 2