Javascript 获取网站的所有 href 属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3871358/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:26:38  来源:igfitidea点击:

get all the href attributes of a web site

javascripthttphrefhyperlink

提问by netha

can anybody tell me a way to get all the href attributes(links) in a web site using javascript?if you could give me a code example, i will be most thankful.

谁能告诉我一种使用 javascript 获取网站中所有 href 属性(链接)的方法吗?如果您能给我一个代码示例,我将不胜感激。

回答by Nick Craver

You can use document.linksto get the anchors, then just loop through grabbing the href, like this:

您可以使用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, you could filter it more before the .push()call on the array if you wanted, but that's the concept for grabbing the links and looping through.

您可以在此处对其进行测试,如果需要,您可以在.push()调用数组之前对其进行更多过滤,但这就是获取链接和循环遍历的概念。

回答by Sarfraz

And here is one way with getElementsByTagName:

这是一种方式getElementsByTagName

var links = document.getElementsByTagName('a');

for(var i = 0; i< links.length; i++){
  alert(links[i].href);
}

回答by Alin Purcaru

Use:

用:

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);
}

回答by Manoj Govindan

One simple wayOne way is to use the document.getElementsByTagNamefunction. For e.g.

一种简单的方法一种方法是使用document.getElementsByTagName函数。例如

document.getElementsByTagName('a');

Update

更新

There is a far easier way. See @Nick Craver's answer.

有一个更简单的方法。请参阅@Nick Craver 的回答