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 获取链接?


基础教程推荐
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- 直接将值设置为滑块 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01