找到<a> tag by text of the href

时间:2017-04-10 08:14:32

标签: jquery href

I want to use jQuery to find a link and hide it . I want to search for the text of the link using jQuery. This doesn't work:

<a href="example.com/foo-bar">a website link</a>
function replace_text() {
  var linkText = jQuery('a').text();
  var answer = linkText.replace('a website link', '');
}
replace_text();

1 个答案:

答案 0 :(得分:4)

要按照文字隐藏元素,您可以使用:contains选择器,然后使用hide(),如下所示:

&#13;
&#13;
$('a:contains("a website link")').hide();
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="example.com/foo-bar">a website link</a>
&#13;
&#13;
&#13;

请注意,以上是不区分大小写的贪婪匹配。如果您想要完全匹配,可以使用filter(),如下所示:

&#13;
&#13;
$('a').filter(function() {
  return $(this).text().trim() == 'a website link';
}).hide();
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="example.com/foo-bar">a website link</a>
&#13;
&#13;
&#13;