ReynierPM ReynierPM - 1 year ago 81
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">
<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>

I am trying to delete the
element by its
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 is.

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

There is a Fiddle here to play with.

Answer Source

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 -----------------------^
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download