开发者

Find text in element and addClass to Parent

开发者 https://www.devze.com 2022-12-09 19:46 出处:网络
HTML: <table> <tr> <td> <a href=\"#\" class=\"nav\">link</a> <td> </tr>

HTML:

<table>
 <tr>
  <td>
   <a href="#" class="nav">link</a>
  <td>
 </tr>
</table>

I want to: FIND TEXT 'link' in a.nav and ADD ID "abc" to 'table'. Tried this but it doesn't work:开发者_运维技巧

$('table>tbody>tr>td>a.nav:contains("Forum Index")').parents('table').attr('id', 'newID');

(tbody because most browsers add it automatically)


Your selection criteria does not need to be so explicit. In fact I would make them as simple as possible while still selecting only the elements that you need. Simple selection criteria will be more performant.

$('a.nav:contains("link")').parents('table').attr('id', 'abc');


Yes, it does work. I tried it with only changing the string in the contains from "Forum Index" to "link", and it does change the id of the table.

However, you shouldn't really change the id of elements. Use a class intead if possible.

0

精彩评论

暂无评论...
验证码 换一张
取 消