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

大兔子大兔子 提交于 2019-12-28 02:51:25

问题


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:


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



回答4:


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.



来源:https://stackoverflow.com/questions/3871358/get-all-the-href-attributes-of-a-web-site

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!