ReynierPM ReynierPM - 2 months ago 13
jQuery Question

Delete row by it's data-* attr does not work, why?

I have the following HTML code:

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

And I am trying to delete the
element by it's
attr. So this is what I am doing:

$(function() {
$('#restricted_component_data').on('click', '.remove_restriction', function(ev) {
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's. Can any help to find out why this is not working? There is a Fiddle here to play with.


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();
// -------------------------------------^^^^^------------------------------------------^


$('#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 -----------------------^