任何人都可以告诉我一种使用javascript获取网站中所有href属性(链接)的方法吗?如果你能给我一个代码示例,我将非常感激。
答案 0 :(得分:54)
您可以使用document.links
获取锚点,然后循环抓取href
,如下所示:
var arr = [], l = document.links;
for(var i=0; i<l.length; i++) {
arr.push(l[i].href);
}
//arr is now an array of all the href attributes from the anchors in the page
You can test it out here,如果您愿意,可以在对数组进行.push()
调用之前对其进行过滤,但这是抓取链接并循环的概念。
答案 1 :(得分:10)
这是getElementsByTagName
的一种方式:
var links = document.getElementsByTagName('a');
for(var i = 0; i< links.length; i++){
alert(links[i].href);
}
答案 2 :(得分:2)
使用:
var anchors = document.getElementsByTagName('a');
var hrefs = [];
for(var i=0; i < anchors.length; i++){
if(1/* add filtering here*/)
hrefs.push(anchors[i].href);
}
答案 3 :(得分:1)
一种简单的方法一种方法是使用document.getElementsByTagName
函数。例如,
document.getElementsByTagName('a');
<强>更新强>
有一种更容易的方法。请参阅@Nick Craver的answer。