jquery find text inside

2019-06-19 08:09发布

问题:

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?

回答1:

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.



回答2:

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.



回答3:

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>