Problem
What is the best jQuery approach for removing a table row?
Asked by Darryl Hein
Solution #1
You’re right:
$('#myTableRow').remove();
If you have an id for your row, such as:
<tr id="myTableRow"><td>blah</td></tr>
If you don’t have an id, any of jQuery’s selectors will suffice.
Answered by imjoevasquez
Solution #2
$('#myTable tr').click(function(){
$(this).remove();
return false;
});
One that is even better
$("#MyTable").on("click", "#DeleteButton", function() {
$(this).closest("tr").remove();
});
Answered by nickf
Solution #3
Assuming you have a button/link inside a table data cell, something like this will suffice…
$(".delete").live('click', function(event) {
$(this).parent().parent().remove();
});
This will delete the parent of the parent of the clicked button/link. You need to use parent() twice because the button is inside a data cell, which is inside a row….which is what you want to delete. It’s a jQuery object, not a standard DOM object, therefore you need to use parent() twice. Because $(this) is the clicked button, having something like this will merely delete the button:
$(this).remove();
While doing so, the following data cell will be removed:
$(this).parent().remove();
Something like this would work if you just want to remove a row by clicking anywhere on it. This may simply be changed to prompt the user or only work when double-clicked:
$(".delete").live('click', function(event) {
$(this).parent().remove();
});
I hope this information is useful… I had some difficulty with this as well.
Answered by sluther
Solution #4
You can use:
$($(this).closest("tr"))
for locating an element’s parent table row
It’s more refined than being a parent (). parent(), which is what I started with and quickly realized was a mistake.
—Revise — The question, it was pointed out, was about eliminating the row…
$($(this).closest("tr")).remove()
You can just do what is outlined below:
$(this).closest('tr').remove();
A code snippet like this can be used for a variety of tasks, such as firing events on numerous items.
Answered by Ian Lewis
Solution #5
Easy.. Try this
$("table td img.delete").click(function () {
$(this).parent().parent().parent().fadeTo(400, 0, function () {
$(this).remove();
});
return false;
});
Answered by Thurein
Post is based on https://stackoverflow.com/questions/170997/what-is-the-best-way-to-remove-a-table-row-with-jquery