user1938320
user1938320

Reputation: 31

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>

Upvotes: 1

Views: 6121

Answers (5)

Icemanind
Icemanind

Reputation: 48686

If you are using jQuery, its as simple as this:

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

Upvotes: 0

speedingdeer
speedingdeer

Reputation: 1236

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 ?

Upvotes: 0

RacerNerd
RacerNerd

Reputation: 1579

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.

Upvotes: 0

speedingdeer
speedingdeer

Reputation: 1236

use

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

instead of

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

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

Upvotes: 0

angeek86
angeek86

Reputation: 108

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
}
}

Upvotes: 2

Related Questions