开发者

get all the href attributes of a web site [duplicate]

This question already has answers here: How to get all the URLs in a web site using JavaScript? 开发者_开发知识库 (5 answers) Closed 6 years ago.

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.


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.


And here is one way with getElementsByTagName:

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

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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜