tags:

views:

368

answers:

2

Hello JavaScript guru's. I have a simple JS question on how to replace all IMG src path's on a page.

Currently, my IMG tags look like:

<img src="path/to/image.jpg" alt="" />

Output desired:

<img src="../image.jpg" alt="" />

So, when a page is loaded, it will loop through all the IMG tags and replace the SRC path. Thanks in advance for the assistance!

+3  A: 
for (var image, src, images = document.images, l=images.length, i=0; i<l; i++){
    image = images[i];
    src = image.src;
    image.src = ".." + src.substring(src.lastIndexOf("/"));
}
Roland Bouman
+1  A: 

What's the application of this? You load the previous images, then reload new images? Just change the src in the html to the new image src. This will save bandwith, work for users with javascript disabled, and be speedier.

(my apologies if you are not asking this question about a real-implementation :)

CrazyJugglerDrummer
There are thousands of static html pages that come from a CMS, then we have to move the images to a different directory (one directory above the web root). One might ask, well why can't we just change the links in the CMS before publishing? We can't, it's a loooong story ;)
Drew
@Drew: A quick fix will need to be truly fixed soon enough. You might be buying a bit of time. Although I totally understand looooong stories.
John K
@JDK - I agree, and we argued against doing this, but the customer want's it this way, and they pay the bills.
Drew
can you change the html pages? You could probably get by with just running a regex on all of them and making sure everything behaved. If it's possible, that might be a better choice.
CrazyJugglerDrummer