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)
var links = document.getElementsByTagName("a");
for (var i = 0; i < links.length; i++) {
links[i].href = "http://example.com";
}
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";
}
var links = document.getElementsByTagName("a");
for (i=0;i<links.length;i++)
links[i].href = "http://example.com";
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/';
}
}
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.
精彩评论