views:

78

answers:

5

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.

+7  A: 

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.

Nick Craver
how can i get links in a web page without loading it? (basically what i want is this. a user enters a URL and i want to load all the available links inside that URL.) can you please tell me a way to achieve this
netha
@netha - That's an entirely different question, are you talking about via AJAX, or server-side? Are you using any frameworks?
Nick Craver
No I'm not using any frame works. i wish to do it in client site (i think server-side will put more burden on server since i wish to do some operations to that links). i just need a way to do this. i will even ready to learn a framework if it does the job. how can i achieve this?
netha
@netha - Are the pages you're getting on your domain, or another? If they're on another you have no choice but to do it server-side, due to security restrictions.
Nick Craver
they are not in my domain. if there is no other way then i guess i have to do it on server-side right? do you know any way to do it from server-side?
netha
@netha - I would ask that as a separate question, including which server platform you're on, it's an *entirely* different answer, so best to be its own SO question.
Nick Craver
I'm using WAMP server and then i guess I'm in apachi platform
netha
+2  A: 

And here is one way with getElementsByTagName:

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

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

Hi,

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);
}
Alin Purcaru
A: 

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.

Manoj Govindan
I would argue against saying this is the simplest :)
Nick Craver
@Nick: Point taken. Amending to "One simple". :)
Manoj Govindan
A: 

ok guys those codes are possible if we are in the page. (i.e if the page is loaded) but what if i want to get links in a given URL?how can i get all the links without loading the page?

netha