Jasper
Jasper

Reputation: 5238

Get image src with jQuery

<img src="../img/arnold.png" alt="Arnold">

How do I get with jQuery absolute path of this image?

img.attr("src") gives me just "../img/arnold.png", should give something like "http://site.com/data/2011/img/arnold.png" (full url).

Upvotes: 27

Views: 93612

Answers (3)

Samir Karmacharya
Samir Karmacharya

Reputation: 890

Give current clicked image source in jQuery

jQuery(document).ready(function($){
$('body').on('click','img',function(){
                alert('it works');
                var imgsrc=$(this).attr('src');
                alert(imgsrc);
});
});

Upvotes: 0

Bradley Staples
Bradley Staples

Reputation: 367

I don't know that you can get it with jQuery, but you can get it with just the native JavaScript image object.

var getSrc = function(imgSource) {
    var img = new Image();
    img.src = imgSource;
    return img.src;
};

Just call it with x = getSrc(srcAttribute) or something similar where your parameter is the string or literal holding the src you currently have in your html/image. It will return something like http://your/site/path/to/image.jpg

http://jsfiddle.net/BradleyStaples/cQMjQ/

Upvotes: 3

Reigel Gallarde
Reigel Gallarde

Reputation: 65254

alert( $('img')[0].src );

this might do the trick... but not sure about cross browser....

demo in here

also try prop of jQuery 1.6..

alert( $('img').prop('src') );

demo here

Upvotes: 64

Related Questions