View Full Version : Replace image source with other source

Nov 23rd, 2009, 12:25 AM
Very new to Javascript (been a HTML/CSS guy for a while, but never really got into more than tinkering with other other people's Javascript coding), but I came across a situation I can't find canned coding for, and trying to create it from bits and pieces I Googled has led me to a dead-end.

In summary, I have a website that I frequently visit (FWIW, Firefox 3.x is my browser of choice) with many image sources referring to URLs that end with "-thumbnail.jpg". However, for better image quality, I am trying to use Greasemonkey to replace all instances of "-thumbnail.jpg" in the source of images on this site with "-bigthumbnail.jpg". The closest I could think of was to somehow use getElementsByTagName and innerHTML.replace, but realized that innerHTML does not do HTML, only content.

Below is as far as I tried to get on my own, I appreciate any assistance from the folks here to help a JS novice like myself, thanks!
(function() {
var as,ae;
as = document.getElementsByTagName("img");
for (var i = 0; i < as.length; i++) {
ae = as[i];
ae.innerHTML = ae.innerHTML.replace(/-thumbnail/gi, "-bigthumbnail");

Nov 23rd, 2009, 11:27 AM
You must change the src attributes of the images:

function replaceSRC(){
var allImg=document.getElementsByTagName('img'), i=0, img;
img.src=img.src.replace(/-thumbnail/gi, "-bigthumbnail");

Nov 24th, 2009, 06:44 AM
Thanks a bundle Kor, that was the missing piece I couldn't figure out! In the end, my code is as follows (adding doInterval so the script would keep looking for changes on the page as the site's coding adds new thumbnails as one browses), cheers!
var doInterval;
function replaceSRC(){
var allImg=document.getElementsByTagName("img"), i=0, img;
img.src=img.src.replace("-thumbnail", "-bigthumbnail");
doInterval = setInterval(replaceSRC,1000);