Search code examples
javascriptappendsrc

append string to image src using js


I've got a page where there is <img src="/images/product/whatever-image.jpg" alt="" />

I want it so that upon loading of the page, the string "?Action=thumbnail" is appended to src's value, making it src="/images/product/whatever-image.jpg?Action=thumbnail"

how do I achieve this using js?


Solution

  • window.addEventListener('load', function(){
        /* assuming only one img element */
        var image = document.getElementsByTagName('img')[0];
    
        image.src += '?Action=thumbnail';
    }, false);
    

    Note, changing the source of the image will "re-fetch" the image from the server — even if the image is the same. This will be better done on the server-side.


    Update after comment:

    window.addEventListener('load', function(){
        /* assuming only one div with class "divclassname" and img is first child */
        var image = document.getElementsByClassName('divclassname')[0].firstChild;
    
        image.src += '?Action=thumbnail';
    }, false);