ReynierPM ReynierPM - 6 days ago 6
Javascript Question

Delete row by its data-* attr does not work, why?

I have the following HTML code:

<table class="table" id="restricted_component_data">
<tbody>
<tr>
<th></th>
<th>Component ID</th>
</tr>
<tr data-component-id="15">
<td>
<span class="remove_restriction" data-component-id="15">X</span>
</td>
<td>link_component_restriction</td>
</tr>
<tr data-component-id="12">
<td>
<span class="remove_restriction" data-component-id="12">X</span>
</td>
<td>link_component_restriction 12</td>
</tr>
<tr data-component-id="11">
<td>
<span class="remove_restriction" data-component-id="11">X</span>
</td>
<td>link_component_restriction 11</td>
</tr>
</tbody>
</table>


I am trying to delete the
tr
element by its
data-component-id
attr. So this is what I am doing:

$(function() {
$('#restricted_component_data').on('click', '.remove_restriction', function(ev) {
ev.preventDefault();
var component_id = $(this).data('component-id');

$('#restricted_component_data').find('tr [data-component-id="' + component_id + '"]').remove();
});
});


But my code isn't working since it only deletes the column and not the row (try it on the Fiddle). I am missing something here but I am not sure what it is.

Can any help to find out why this is not working?

There is a Fiddle here to play with.

Answer

If possible, I would do it via traversal, as shown in Sachin's answer.

If for some reason you can't do that:

The reason what you have isn't working is you're only matching the td, not the tr, because your selector is for elements with that attribute that are within (descendants of) the tr.

Instead of

$('#restricted_component_data').find('tr [data-component-id="' + component_id + '"]').remove();

you want

$('#restricted_component_data').find('tr:has([data-component-id="' + component_id + '"])').remove();
// -------------------------------------^^^^^------------------------------------------^

or

$('#restricted_component_data').find('tr [data-component-id="' + component_id + '"]').closest('tr').remove();
// ----------------------------------------------------------------------------------^^^^^^^^^^^^^^

or as Eun points out in a comment, since that same data attribute is on the tr as well as the td, you can just use your original code but with the space after tr removed:

$('#restricted_component_data').find('tr[data-component-id="' + component_id + '"]').remove();
// No space here -----------------------^