How to efficiently change image attribute “src” from relative URL to absolute using jQuery?

I need to change the src for an html image tag from relative to absolute url.

I am using the following code. urlRelative and urlAbsolute are created correctly but I cannot modify the image in the last line.

What could be wrong wrong in my script?

..... // other code here

     request.done(function(resp) {
            var imgTags = $('img', resp).each(function() {
                var urlRelative = $(this).attr("src");
                var urlAbsolute = self.config.proxy_server + self.config.location_images + urlRelative;
                $(this).attr("src").replace(urlRelative, urlAbsolute); // problem here

Try like this

$(this).attr("src", urlAbsolute)

Try $(this).attr("src", urlAbsolute);

jQuery("#my_image").attr("src", "first.jpg")

used this code for src

$(this).attr("src", urlAbsolute);


Instead of below code:

$(this).attr("src").replace(urlRelative, urlAbsolute);

Use this:


Your code can simplified a lot to

$('img', resp).attr('src', function(idx, urlRelative ) {
    return self.config.proxy_server + self.config.location_images + urlRelative;

The replace method in Javascript returns a value, and does not act upon the existing string object. See:

In your example, you will have to do

$(this).attr("src", $(this).attr("src").replace(...))

change image captcha refresh


 <img id="captcha_img" src="http://localhost/captcha.php" /> 


        var capt_rand=Math.floor((Math.random() * 9999) + 1);
        $("#captcha_img").attr("src","http://localhost/captcha.php?" + capt_rand);

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   Saving text in a local file in Internet Explorer 10

Similar Posts