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
2010-10-06 10:03:43
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
2010-10-06 14:50:46
@netha - That's an entirely different question, are you talking about via AJAX, or server-side? Are you using any frameworks?
Nick Craver
2010-10-06 14:53:42
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
2010-10-06 15:24:29
@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
2010-10-06 15:27:43
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
2010-10-06 15:33:37
@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
2010-10-06 15:39:38
I'm using WAMP server and then i guess I'm in apachi platform
netha
2010-10-06 15:42:36
+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
2010-10-06 10:04:13
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
2010-10-06 10:04:54
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
2010-10-06 10:05:46
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
2010-10-06 14:42:58