Fi" /> Fi" /> Fi"/>

how to remove a tr where td has a certain data-attr value

36 views Asked by At

I am trying to remove a tr from DOM after ajax success where td of this tr has a certain data-value value

This is the html:

<tr>
    <td data-value="1">First</td>
</tr>
<tr>
    <td data-value="2">Second</td>
</tr>
<tr>
    <td data-value="3">Third</td>
</tr>
......

My ajax javascript:

success: function (data) {          
            var identity = data.val; // gives me the number 2
            // find td which has data-value of 2 and remove the corresponding tr of it from DOM 
            $('td[data-value=identity]').closest('tr').remove(); // does not work       
        },

How can i achieve this?

1

There are 1 answers

0
Ask Athar On

I would recommend you to be very specific about the table in which it has that 'td' tag.

$('td[data-value="'+ identity +'"]').closest('tr').remove();

The above code which was answered in the comment will work well for you only:

  • If you have single table in the HTML DOM with 'tr' tag as parent element to 'td' tag having data-value='identity' on it.
  • If there are multiple table on the HTML DOM, this code will check from the start/very first 'element' inside the DOM as soon as it will find 'td' tag with data-value='identity' attribute, it will remove the parent 'tr' element irrespective of there may be multiple table inside DOM OR you were expecting to remove 'tr' tag from table 2 but it removed the 'tr' tag from table 1 as per above code.

It's always a nice practice to specify table name in your jQuery selector & traverse it to particular child element as per requirements, if you want to target any tag inside of a table (as there can be multiple table on a same page in future developments).

You can improvise above code as,

$('#specific-table-name tbody td[data-value="'+ identity +'"]').closest('tr').remove();

This code will first find the table name inside of entire DOM then traverse to 'tbody' tag of that table & search for 'td' element which has data-value="identity" -> then remove the closest 'tr'.

NOTE: If you want to remove multiple data-value="identity", use .each/.map method to iterate over table for desired results.