get all the href attributes of a web site [duplica

2019-01-09 01:05发布

This question already has an answer here:

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.

4条回答
霸刀☆藐视天下
2楼-- · 2019-01-09 01:14

One simple way One way is to use the document.getElementsByTagName function. For e.g.

document.getElementsByTagName('a');

Update

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

查看更多
我只想做你的唯一
3楼-- · 2019-01-09 01:16

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

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.

查看更多
▲ chillily
4楼-- · 2019-01-09 01:19

And here is one way with getElementsByTagName:

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

for(var i = 0; i< links.length; i++){
  alert(links[i].href);
}
查看更多
贪生不怕死
5楼-- · 2019-01-09 01:23

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);
}
查看更多
登录 后发表回答