b85411
b85411

Reputation: 10010

jQuery - find TD with matching contents, then find the closest TD to that

Below is an example of a table I have.

What I want is a jQuery that will search the first column for ID = 16, and then find the contents of the column two columns to the right of that (ie. 105 L in this case).

It might not always be the number 16, but in this scenario it will always be the column 2 to the right of whichever ID I choose (ie. the column with the colspan=3 on it).

Is this possible?

      <tr>
        <td class="table-inner report-centre">15</td>
        <td class="table-inner">Question here </td>
        <td class="centre"></td>
        <td class="centre danger"><span class="glyphicon glyphicon-ok"></span></td>
        <td class="centre"></td>
      </tr>
      <tr>
        <td class="table-inner report-centre">16</td>
        <td class="table-inner">Amount here </td>
        <td class="table-inner" colspan="3">105 L</td>
      </tr>
      <tr>
        <td class="table-inner report-centre">17</td>
        <td class="table-inner">Is everything okay? </td>
        <td class="centre success"><span class="glyphicon glyphicon-ok"></span></td>
        <td class="centre"></td>
        <td class="centre"></td>
       </tr>

Upvotes: 1

Views: 152

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388326

You could do something like

var value = 16
var l = $('td:first-child').filter(function(){
    return $(this).text().trim() == value;
}).siblings(':nth-child(3)').text();

console.log(l)

Demo: Fiddle

I won't recommend :contains here as it can return partial matches


If you want to find the td with colspan=3, then use the attribute equals selector

var value = 16
var l = $('td:first-child').filter(function(){
    return $(this).text().trim() == value;
}).siblings('[colspan=3]').text();

Demo: Fiddle

Upvotes: 2

Related Questions