jquery find text inside <td>

徘徊边缘 提交于 2019-12-23 10:07:36

问题


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>


来源:https://stackoverflow.com/questions/4073427/jquery-find-text-inside-td

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!