选择<a> which href ends with some string</a>

时间:2008-11-20 00:23:59

标签: jquery string

是否可以使用jQuery选择href以“ABC”结尾的所有<a>个链接?

例如,如果我想找到此链接<a href="http://server/page.aspx?id=ABC">

4 个答案:

答案 0 :(得分:1495)

   $('a[href$="ABC"]')...

选择器文档可在http://docs.jquery.com/Selectors

找到

对于属性:

= is exactly equal
!= is not equal
^= is starts with
$= is ends with
*= is contains
~= is contains word
|= is starts with prefix (i.e., |= "prefix" matches "prefix-...")

答案 1 :(得分:19)

$('a[href$="ABC"]:first').attr('title');

这将返回第一个链接的标题,该链接的URL以“ABC”结尾。

答案 2 :(得分:14)

$("a[href*='id=ABC']").addClass('active_jquery_menu');

答案 3 :(得分:0)

如果您不想导入像jQuery这样的大库来完成这一琐碎的事情,则可以使用内置方法querySelectorAll来代替。几乎所有用于jQuery的选择器字符串都可以使用DOM方法:

const anchors = document.querySelectorAll('a[href$="ABC"]');

或者,如果您知道只有一个匹配元素:

const anchor = document.querySelector('a[href$="ABC"]');

如果要搜索的值是字母数字,通常可以省略属性值周围的引号,例如,在这里,您也可以使用

a[href$=ABC]

但引号更灵活,generally more reliable

相关问题