Search code examples
htmlimagesrc

Efficient way to change the image of img tag without editing the html?


I have a page that shows search results of downloadable files. Beside each search result, I have an icon to denote the file type like so:

<img src="/icons/ugly/powerpoint.gif" />

I want to change the /icons/ugly/powerpoint.gif to /icons/pretty/powerpoint.gif but I am not allowed to modify the HTML. What is the best way to use /icons/pretty/powerpoint.gif instead of /icons/ugly/powerpoint.gif?

An idea I had was to use javascript to do this after I load the page, but not sure if this is a good idea.


Solution

  • There are two options, if you cannot edit the HTML.

    1) Server side, modify the image retrieved, possibly via the use of URL rewriting.

    RewriteRule ^(.*)/ugly/(.+\.gif)$ $1/pretty/$2 [L]
    

    2) Client side, alter the src attribute, using JavaScript, or some library tool on top of JavaScript, like jQuery.

    jQuery code to process all images to achieve this would be:

    $('img').attr('src', function(i, src) {
       return src.replace(/\/ugly\//, '/pretty/');
    });