Jquery find text inside <td>
I play with some selectors and I click on the wall, selecting the text inside the cell.
Here is a simple attempt that I am making.
<table> <tr> <td>First Name</td> <td>*required</td> </tr> </table> I want to change the class for this cell as "red" - if the string "* required" is found.
Here is my jquery attempt:
$("td:contains('*required')").addClass("red"); This makes all cells apply this class, it seems. Any more efficient ways to search for specific text?
You have works, you can test it here , keep in mind that any parent <td> also contains this text, although for exact correspondence do this
$("td").filter(function() { return $.text([this]) == '*required'; }) .addClass("red"); You can always just use $.filter() , where only those elements that return true are included in the selection. For example:
$('td').filter(function(i) { $(this).html().indexOf('*required') >= 0; }); Also: you want to be more specific with your selector - for efficiency, and also because of Nick's answer. Although, if you are considering efficiency, you better not use a method that uses a callback in the first place. :)
As for selectors, consider using $('#tableID > tr > td')... or something similar.
You should not use JavaScript for this. What you should use is a CSS class:
<table> <tr> <td>First Name</td> <td class="required">*required</td> </tr> </table> <style type="text/css"> td.required { color:red; } </style>