简体   繁体   中英

Changing all links on page

I want to change all links on page, it works with links that have no class, but it won't work with links that have class.

This is the code I am using:

window.onload = function() {
       /* onload code */

var anchors = document.getElementsByTagName("a");

for (var i = 0; i < anchors.length; i++) {
    anchors[i].href = "http://www.example.com/?redirect=" + anchors[i].href
}
}

It works for links such as:

<a id="box-left" href="http://www.google.com"></a>

But doesn't work for this:

<a class="links" href="redirect.php?link=125411" onclick="launch();" target="_blank"></a>

I think that the correct function should be :

window.onload = function() {
   /* onload code */

var anchors = document.getElementsByTagName("a");

for (var i = 0; i < anchors.length; i++) {
    anchors[i].href = "http://www.mysite.com/?redirect=" + anchors[i].href
}
}

use

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

instead of

var anchors = document.getElementsByTagName("class");

BTW I recommend you to use jquery to select dom elements.

I tested the code as it is posted and it worked for me.
I put the javascript in a tag and the links in the body.
Maybe there is something else on the page interfering.

Maybe you have some strange CSS whick mix something with this link with this class="links" attribute? You can also try add class to both kind of links and select by class.

var anchors = document.getElementsByClassName("dynamic_links");

<a id="box-left" class="dynamic_links" href="http://www.google.com"></a> 

<a class="links dynamic_links" href="redirect.php?link=125411" onclick="launch();" target="_blank"></a>

Let me know what about this ok ?

如果您使用的是jQuery,则其操作非常简单:

$('a').attr("href", "http://www.google.com/")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM