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


基础教程推荐
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01