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

我想通过 jquery 或 javascript 中的 href 属性获得一个元素,这可能吗?

167683 次浏览

Yes.

$('a[href=\'http://google.com\']')

http://api.jquery.com/attribute-equals-selector/

var myElement = $("a[href='http://www.stackoverflow.com']");

http://api.jquery.com/attribute-equals-selector/

Yes, you can use jQuery's attribute selector for that.

var linksToGoogle = $('a[href="https://google.com"]');

Alternatively, if your interest is rather links starting with a certain URL, use the attribute-starts-with selector:

var allLinksToGoogle = $('a[href^="https://google.com"]');

If you want to get any element that has part of a URL in their href attribute you could use:

$( 'a[href*="google.com"]' );

This will select all elements with a href that contains google.com, for example:

As stated by @BalusC in the comments below, it will also match elements that have google.com at any position in the href, like blahgoogle.com.