Saturday, March 30, 2013

jquery find element contains text

eq expects a numerical index to only return a single row. If you want to match a td by its contents, you have to use the :contains selector. Saying "it doesn't work" and throwing it away is not the right approach to the problem, as the selector is (most likely) not at fault (Do note its case sensitive, which might be it...)
Anyhow, if you have a table like this:
<table>
  <tr>
    <td>Hello</td>
    <td>World</td>
  </tr>
  <tr>
    <td>World</td>
    <td>Hello</td>
  </tr>
  <tr>
    <td>Hello</td>
    <td>Hello</td>
  </tr>
</table>
This jQuery code:
$(function() {
    $("td:contains('Hello')").css('color','red');
});
Will turn all cells with "Hello" to red. Demo.
If you need a case insensitive match, you could do this, using the filter function:
$(function() {
    var search = 'HELLO'.toLowerCase();
    $("td").filter(function() {
        return $(this).text().toLowerCase().indexOf(search) != -1;
    }).css('color','red');
});
If you need to match the exact contents of the cell, you could use something similar to the above:
$(function() {
    var search = 'HELLO'.toLowerCase();
    $("td").filter(function() {
        return $(this).text().toLowerCase() == search;
    }).css('color','red');
});
The above is case insensitive (by turning both the search and the contents to lower case when comparing) otherwise you can just remove those if you want case sensitivity. Demo.

No comments:

Post a Comment