Javascript 如何通过jquery中的href获取元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3105984/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get an element by its href in jquery?
提问by eos87
I want to get an element by its href attribute in jquery or javascript. Is that possible?
我想通过 jquery 或 javascript 中的 href 属性获取元素。那可能吗?
回答by BalusC
Yes, you can use jQuery's attribute selectorfor that.
是的,您可以为此使用 jQuery 的属性选择器。
var linksToGoogle = $('a[href="http://google.com"]');
Alternatively, if your interest is rather links startingwith a certain URL, use the attribute-starts-withselector:
或者,如果您更喜欢以某个 URL开头的链接,请使用属性开始选择器:
var allLinksToGoogle = $('a[href^="http://google.com"]');
回答by JCM
If you want to get any element that has part of a URL in their href attribute you could use:
如果您想获取在其 href 属性中包含部分 URL 的任何元素,您可以使用:
$( 'a[href*="google.com"]' );
This will select all elements with a href that contains google.com, for example:
这将选择所有带有包含 google.com 的 href 的元素,例如:
- http://google.com
- http://www.google.com
- https://www.google.com/#q=How+to+get+element+by+href+in+jquery%3F
- http://google.com
- http://www.google.com
- https://www.google.com/#q=How+to+get+element+by+href+in+jquery%3F
As stated by @BalusC in the comments below, it will also match elements that have google.comat any position in the href, like blahgoogle.com.
正如@BalusC 在下面的评论中所述,它还将匹配google.com在 href 中任何位置的元素,例如blahgoogle.com.
回答by Adam
var myElement = $("a[href='http://www.stackoverflow.com']");

