tags:

views:

76

answers:

5

A page has many tags. How do I loop through all of them and replace their "href" with "http://example.com"?

(do not use jQuery)

+2  A: 

You must use getElementsByTagName() to fetch all the links, and then loop through them to change the href property.

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

if(links) { // if none are found, do not continue
    for(var i = 0; i < links.length; i++) {
        links[i].href = 'http://example.com/';
    }
}
Andrew Moore
+2  A: 
var links = document.getElementsByTagName("a");
for (i=0;i<links.length;i++)
    links[i].href = "http://example.com";
F.Aquino
+10  A: 
var links = document.getElementsByTagName("a"); 
for (var i = 0; i < links.length; i++) { 
    links[i].href = "http://example.com";
}
Mike Sherov
+4  A: 

You can use the document.links collection. It's defined by the W3C and supported by all common browsers.

Moreover you get access not only to <a> elements, but to <area> tags too (which are commonly used in client image maps).

for(var i=0; i < document.links.length; i++) {
   document.links[i].href = "http://example.com";
}
Andrea Zilio
+1  A: 
for(var i=0,L=document.links.length;i <L; i++) {
   document.links[i].href = "http://example.com";
}

Or load a 20 kb library and write a little less code.

kennebec
I'm sorry, this is the same as a previous answer.
kennebec