【问题标题】:Is it possible to grab a link by its href if it doesn't have a class or ID?如果没有类或 ID,是否可以通过其 href 获取链接?
【发布时间】:2012-10-01 03:34:02
【问题描述】:
我正在使用其他人的应用程序,并希望更改任何具有特定 href 的 标记之间的内部 HTML。但是这些链接没有与之关联的类或 ID,我无法编辑代码来为它们提供类或 ID。有没有办法通过 JavaScript 中的 href 来获取标签?我想做类似的事情:
var theLink = document.getElementByHref("example.com");
否则,如果不可能,我可以遍历页面中的所有链接并选择具有我要查找的特定 href 和 innerHTML 的链接吗?
【问题讨论】:
标签:
javascript
jquery
html
tags
【解决方案1】:
选择href 属性中具有 example.com 值的所有元素:
现场演示: http://jsfiddle.net/NTGQz/
$('a[href*="example.com"]');
您也可以试试这个,只是为了更具体并遵循 OP “理想” 答案:
现场演示: http://jsfiddle.net/ksZhZ/
jQuery.fn.getElementsByHref = function(str){ return $('a[href*="' + str + '"]'); };
$(document).ready(function(){
elems = $(this).getElementsByHref('example.com');
});
【解决方案2】:
您可以使用 DOM3-attribute-selector (jQuery doc) 来获取在其 href 属性中包含特定文本的所有元素。它看起来像
$('a[href*="example.com"]')
但是,这可能不是您真正想要的 - 不仅该域的 url 可能包含此字符串。你可能会做类似开头的事情:
$('a[href^="http://example.com"]')
但要获得精确且可能更复杂的匹配,您不能绕过自定义filter:
$('a[href]').filter( function() {
return this.hostname == "example.com";
// or check other properties of the anchor element
})
【解决方案3】:
如果您的用户在 IE8+ or any other browser 上,您可以使用 querySelectorAll 在本机上执行此操作。此方法返回匹配元素的 NodeList。
document.querySelectorAll('a[href="exact/value.html"]'); // exact match
document.querySelectorAll('a[href*="partial/value.html"]'); // partial match
document.querySelectorAll('a[href^="starts/with"]'); // href starts with
document.querySelectorAll('a[href$=".html"]'); // href ends with
【解决方案4】:
你可以在没有 jQuery 的情况下做到这一点。
var links = document.querySelectorAll('a[href*="example.com"]');
【解决方案6】:
$('a[href="http:google.com"]')
【解决方案7】:
试试这个
$('a[href*="example.com"]');
这将选择在 href 属性中包含 example.com 的链接..
【解决方案9】:
您可以使用属性选择器:
$('a[href="http://example.com"]')