How to get an element by its href in jquery?

百般思念 提交于 2019-11-26 19:13:27

问题


I want to get an element by its href attribute in jquery or javascript. Is that possible?


回答1:


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

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

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

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



回答2:


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:

  • 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.com at any position in the href, like blahgoogle.com.




回答3:


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

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




回答4:


Yes.

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

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



来源:https://stackoverflow.com/questions/3105984/how-to-get-an-element-by-its-href-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!