如何通过jquery中的href获取元素?

eos*_*s87 94 html javascript jquery javascript-framework

我想通过jquery或javascript中的href属性获取一个元素.那可能吗?

Bal*_*usC 193

是的,您可以使用jQuery的属性选择器.

var linksToGoogle = $('a[href="http://google.com"]');
Run Code Online (Sandbox Code Playgroud)

或者,如果您感兴趣的是某个URL 开始的链接,请使用attribute-starts-with选择器:

var allLinksToGoogle = $('a[href^="http://google.com"]');
Run Code Online (Sandbox Code Playgroud)


JCM*_*JCM 16

如果您想在其href属性中获取包含URL的任何元素,您可以使用:

$( 'a[href*="google.com"]' );
Run Code Online (Sandbox Code Playgroud)

这将选择包含google.com的href的所有元素,例如:

正如@BalusC在下面的评论中所述,它也会匹配google.comhref中任何位置的元素,比如blahgoogle.com.