开发者

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

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 p开发者_JS百科age) {

  doSomething (URL(i));

}

thanks


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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜