如果没有类或 ID,是否可以通过其 href 获取链接?

2022-01-18 00:00:00 tags jquery javascript html

我正在使用其他人的应用程序,并希望在任何 < 之间更改 innerHTMLa> 具有特定 href 的标签.但是这些链接没有与之关联的类或 ID,我无法编辑代码来为它们提供类或 ID.有没有办法通过 JavaScript 中的 href 来获取标签?我想做类似的事情:

I'm using someone else's app and want to change the innerHTML in between any < a>< /a> tag that has a certain href. But these links don't have a class or ID associated with them and I can't edit the code to give them classes or ID's. Is there a way to grab a tag by its href in JavaScript? I wanted to do something similar to this:

var theLink = document.getElementByHref("example.com");

否则,如果不可能,我可以遍历页面中的所有链接并选择具有我要查找的特定 href 和 innerHTML 的链接吗?

Otherwise, if that is not possible, can I loop through all the links in the page and choose the ones that have the certain href and innerHTML I'm looking for?

推荐答案

你可以使用 DOM3-attribute-selector (jQuery doc) 以获取在其 href 属性中包含特定文本的所有元素.它看起来像

You can use a DOM3-attribute-selector (jQuery doc) to get all elements that contain a certain text in their href attribute. It would look like

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

但是,这可能不是您真正想要的 - 不仅该域的 url 可能包含此字符串.你可能会做类似开头的事情:

However, that might not be what you actually want - not only urls to that domain might contain this string. You might do something like begins-with:

$('a[href^="http://example.com"]')

但要获得精确且可能更复杂的匹配,您不能绕过自定义 过滤器:

but to get an exact and possibly more complex match, you don't get around a custom filter:

$('a[href]').filter( function() {
     return this.hostname == "example.com";
     // or check other properties of the anchor element
})

相关文章