Lina
Lina

Reputation: 627

Find if table has a specific string in jquery

I have a html table:

Name   Length Description  x
Name1  444    Blabd        x.png
Name2  55     Blabla       x.png
Name3  11     Blaaa        x.png

table id="firsttable" img class="delete"

I have a value (from other table):

var value = $(this).closest('tr').find('td:first').html();

I want to find that value in first column of a table and delete x.png of a row, which has that value.

Something like: (with mistakes)

$('#firsttable tr td:first:contents("'+value+'")').closest('tr').find('td:last').remove();

Upvotes: 2

Views: 5151

Answers (1)

Didier Ghys
Didier Ghys

Reputation: 30666

A few things:

  • use the :first-child selector and not :first.
  • you should use :contains and not :contents (i don't think there is even a :contents() selector - or maybe via a plugin) (see note)
  • .siblings() will find the siblings of the current element which is the first TD. You can pass a selector to limit the selection so pass :last to get oly the last one. Makes more sense than going back to the parent and find the last TD.
  • you can empty the last TD content instead of removing the td element (but you can remove it if you want)

Here's the code:

$('#firsttable td:first-child:contains("' + value + '")')
    .siblings(':last')
    .text('');

DEMO

Note:

:contains will search in text nodes id the specified value is contained, not the exact value! So if you do :contains("1") but you have a TD with value "14", it will find it also. If this is a problem you can use .filter():

$('#firsttable td:first-child').filter(function() {
        return $(this).text() === value;
    })
    .siblings(':last')
    .text('');

More info on:

Upvotes: 6

Related Questions