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

时间:2012-10-10 15:35:49

标签: javascript jquery html tags

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

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

否则,如果无法做到这一点,我是否可以遍历页面中的所有链接并选择具有我正在寻找的特定href和innerHTML的链接?

10 个答案:

答案 0 :(得分:2)

您可以使用DOM3属性选择器(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
})

答案 1 :(得分: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 :(得分:0)

jQuery有a lot of selectors。你想要的是属性选择器。

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

答案 3 :(得分:0)

您可以使用属性选择器:

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

答案 4 :(得分:0)

使用JQuery attribute selector,您可以这样做:

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

答案 5 :(得分:0)

试试这个

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

这将选择href属性中包含example.com的链接..

答案 6 :(得分:0)

$('a[href="http:google.com"]')

答案 7 :(得分:0)

你可以用jquery:http://api.jquery.com/attribute-equals-selector/

来做

ex:linksToGoogle = $('a [href =“http://google.com”]');

答案 8 :(得分:0)

你可以在没有jQuery的情况下做到这一点。

var links = document.querySelectorAll('a[href*="example.com"]');

答案 9 :(得分:0)

如果您的用户在querySelectorAll,您可以使用IE8+ or any other browser本地执行此操作。此方法返回匹配元素的 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
相关问题