Get image src with jQuery

92,565

Solution 1

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

Solution 2

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/

Share:
92,565

Related videos on Youtube

Jasper
Author by

Jasper

Updated on July 22, 2022

Comments

  • Jasper
    Jasper almost 2 years
    <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).

    • PPShein
      PPShein almost 13 years
      It's depend on how did you assign image path in image src.
  • Peter Munnings
    Peter Munnings almost 13 years
    +1 This is very neat - Steve this looks like the correct answer to me
  • V15HM4Y
    V15HM4Y almost 11 years
    Great answer. What should I do, if i want src of all the images in a page?
  • Reigel Gallarde
    Reigel Gallarde almost 11 years
    @V15HMAY: you can use .map() like this... jsfiddle.net/reigel/caVYd/109 look at the console on that sample link.. .map()
  • Alastair
    Alastair over 10 years
    Hmmm...not very efficient, compared to the accepted answer but it is a novel approach!