Chandana Chandana - 7 months ago 9
Javascript Question

Find td text in HTML table next to a td

I am trying to find the text inside table td next to a td with text "My Metadata".
I am trying to loop through table tds etc. to find this. Is there any very simple way to search text inside td which is next to td with some value?

Here is my fiddle

<table id="searchTable">
<tr>
<td>
My Metadata
</td>
<td>
I want to alert this td text which is next to td which has text My Metadata
</td>
</tr>
</table>

Answer

You can use :contains() and next()

  • Using :contains() selector you can get element which contains certain text.
  • Then use next() to get the sibling next to it.

$('#searchTable td:contains(My Metadata)').next().css('color', 'red');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="searchTable">
  <tr>
    <td>
      My Metadata
    </td>
    <td>
      I want to alert this td text which is next to td which has text My Metadata
    </td>
  </tr>
</table>

If you want to select element with exact match then use filter()

$('#searchTable td').filter(function() {
  return $.trim($(this).text()) == 'My Metadata';
}).next().css('color', 'red');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="searchTable">
  <tr>
    <td>
      My Metadata
    </td>
    <td>
      I want to alert this td text which is next to td which has text My Metadata
    </td>
  </tr>
</table>

Comments