get all the href attributes of a web site [duplica

2019-01-09 01:12发布

问题:

This question already has an answer here:

  • get all the URLs in a web site using javascript 2 answers

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.

回答1:

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.



回答2:

And here is one way with getElementsByTagName:

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

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


回答3:

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.



回答4:

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