user3852152 user3852152 - 2 months ago 14
jQuery Question

Matching strings in jQuery

I have this table

<table>
<tr>
<td>Name</td>
<td>John Stevenson</td>
</tr>
<tr>
<td>Name</td>
<td>John Stevenson</td>
</tr>
<tr>
<td>Name</td>
<td>Jack Stevenson</td>
</tr>
</table>


How can I find if there is "Jack Stevenson" and if it true, set this td color to red.

My jQuery code not works:

$("table").find("td").each(function () {
var hiImJohn = $("td:contains('John Stevenson')");
var td = $(this).text();

if ( td.indexOf("John Stevenson") > 0 ) {
hiImJohn.css({color: "red"});
}
});

Answer

Try following

$("table").find("td:contains('John Stevenson')").each(function () {
  $(this).css({color: "red"});
});

For reference - http://plnkr.co/edit/q45cGWpW8ql7FfoNaKDj?p=preview

EDIT

Please note, there is no need of each loop either. Updated code will be as follows

$("table").find("td:contains('John Stevenson')").css({color: "red"});