最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript - how do I iterate thru all URLs of a given page - Stack Overflow

programmeradmin2浏览0评论

I am not experienced in Javascript. After the page finishes loading, I need to iterate thru all URLs a given page and perform some cleanings.

How do I do that?

Something like

for i = 0 to (number of URLS on the page) {

  doSomething (URL(i));

}

thanks

I am not experienced in Javascript. After the page finishes loading, I need to iterate thru all URLs a given page and perform some cleanings.

How do I do that?

Something like

for i = 0 to (number of URLS on the page) {

  doSomething (URL(i));

}

thanks

Share Improve this question asked Dec 23, 2010 at 13:32 DuckDuck 36k48 gold badges265 silver badges489 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 19

If you want to link through all anchors, use document.links, like this:

for(var i = 0, l=document.links.length; i<l; i++) {
  doSomething(document.links[i].href);
}

This is a collection already maintained by the browser (for prefetching under the covers mostly, but other reasons as well)...no need for a document.getElementsByTagName() here. Note: this also gets <area> elements, as long as they have a href attribute...also a valid form of navigation.

I'd always recommend having jQuery around for times like this as it makes it far easier.

For example on page load:

$(document).ready(function(){
    $('a').each(function(index) {
        alert(index + ': ' + $(this).text());
    });
});

Use this function:

var anchors = document.getElementsByTagName("a");
for (anchor in anchors){ 
  doSomething(anchor):
}

Or just plain Javascript with a bit of readability:

var myURL = document.getElementsByTagName('a');
for(var i=0; i<myURL.length; i++)
    console.log(myURL[i].getAttribute('href'));
发布评论

评论列表(0)

  1. 暂无评论