Is it possible to grab a link by its href if it doesn#39;t have a class or ID?(如果没有类或 ID,是否可以通过其 href 获取链接?)
问题描述
我正在使用其他人的应用程序,并希望在任何 < 之间更改 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
})
这篇关于如果没有类或 ID,是否可以通过其 href 获取链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如果没有类或 ID,是否可以通过其 href 获取链接?


- 400或500级别的HTTP响应 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Fetch API 如何获取响应体? 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01