coffeemonitor
coffeemonitor

Reputation: 13120

jquery find text inside <td>

I'm playing around with some selectors, and I'm hitting a wall with selecting Text inside a cell.

Here's a simple attempt I'm making.

<table>
 <tr>
     <td>First Name</td>
     <td>*required</td>
  </tr>
</table> 

I want to change the class for that cell to be "red" - if the string "*required" is found.

Here's my attempt at the jquery:

$("td:contains('*required')").addClass("red");

It's causing all cells to apply that class, it seems. Any better ways to look for specific text?

Upvotes: 6

Views: 32485

Answers (3)

SnickersAreMyFave
SnickersAreMyFave

Reputation: 5143

You should not be using JavaScript to do this. What you should be using 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>

Upvotes: -2

mway
mway

Reputation: 4392

You could always just use $.filter(), where only elements that the callback returns true for are included in the selection. For example:

$('td').filter(function(i) {
    $(this).html().indexOf('*required') >= 0;
});

Also: you'll want to be more specific with your selector - for efficiency, and also because of Nick's answer. Though if you're considering efficiency, you're better off not using a method that uses a callback in the first place. :)

As far as selectors go, consider using $('#tableID > tr > td')... or something similar.

Upvotes: 5

Nick Craver
Nick Craver

Reputation: 630349

What you have works, you can test it here, keep in mind that any parent <td> also contains that text though, to do an exact match do this:

$("td").filter(function() { return $.text([this]) == '*required'; })
       .addClass("red");

You can test it here.

Upvotes: 23

Related Questions