...

View Full Version : Replace links on a page with javascript



I_Love_Privacy
08-21-2008, 10:20 PM
Say on my page I have <img src="http://example.com/a.gif"><a href="http://example.com"></a>

How would I change http://example.com with javascript.

I tried replacing it with document.write search for example.com but it wouldnt work..

document.write(str.replace(/example.com/, "example2.com"));

Any ideas?

Arty Effem
08-22-2008, 01:09 AM
Say on my page I have <img src="http://example.com/a.gif"><a href="http://example.com"></a>

How would I change http://example.com with javascript.

I tried replacing it with document.write search for example.com but it wouldnt work..

document.write(str.replace(/example.com/, "example2.com"));

Any ideas?You need to assign each element an ID attribute, then use document.getElementById to address each element and write to its src or href property as appropriate.

Bill Posters
08-22-2008, 10:38 AM
if you don't need to target specific images and anchors, you could simply loop/iterate through img and [/i]a[/i] elements, checking the src and href values respectively, changing instances of example.com to example2.com.

(rough) e.g.

var aEls = document.getElementsByTagName('a');
for (var i = 0, aEl; aEl = aEls[i]; i++) {
aEl.href = aEl.href.replace('example.com','example2.com');

}

var imgEls = document.getElementsByTagName('img');
for (var i = 0, imgEl; imgEl = imgEls[i]; i++) {
imgEl.src = imgEl.src.replace('example.com','example2.com');

}

Alternatively, if you want to be more specific, you can still do so without needing to add any attributes to the targeted images and anchors, by targeting them as a child of a parent element.

(rough) e.g.

var aEls = document.getElementById('targtDiv').getElementsByTagName('a');
for (var i = 0, aEl; aEl = aEls[i]; i++) {
aEl.href = aEl.href.replace('example.com','example2.com');

}

var imgEls = document.getElementById('targtDiv').getElementsByTagName('img');
for (var i = 0, imgEl; imgEl = imgEls[i]; i++) {
imgEl.src = imgEl.src.replace('example.com','example2.com');

}



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum