How to use regular javascript to view each <a> tag and modify href?

There are many tags on the page. How do I go through all of them and replace their "href" with " http://example.com "?

(do not use jQuery)

+3
source share
5 answers
var links = document.getElementsByTagName("a"); 
for (var i = 0; i < links.length; i++) { 
    links[i].href = "http://example.com";
}
+12
source

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

In addition, you get access not only to elements <a>, but also to tags <area>(which are commonly used in client image cards).

for(var i=0; i < document.links.length; i++) {
   document.links[i].href = "http://example.com";
}
+4
source

getElementsByTagName(), , , href.

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

Or download the 20 kb library and write a little less code.

+1
source

Source: https://habr.com/ru/post/1731818/


All Articles