16

Using Javascript, is there a standard way to get the absolute path of an image? img.getAttribute("src") only returns the src attribute as it was declared in the HTML.

Elias Zamaria
  • 96,623
  • 33
  • 114
  • 148
Pierre
  • 34,472
  • 31
  • 113
  • 192

2 Answers2

23

Just do .src.

$('img')[0].src = '/images/foo.gif'
"/images/foo.gif"
$('img')[0].src
"http://stackoverflow.com/images/foo.gif"
$('img')[0].getAttribute('src')
"/images/foo.gif"
meder omuraliev
  • 183,342
  • 71
  • 393
  • 434
  • 2
    To clarify - `.src` actually does convert relative paths to absolute. Example: `var a = new Image(); a.src = '/a/../b'; alert(a.src)` will resolve correctly. – Jamie Wong Aug 16 '10 at 19:21
  • Thanks, that was so obvious :-)) – Pierre Aug 16 '10 at 19:23
  • When in doubt, check the [spec](https://html.spec.whatwg.org/multipage/embedded-content.html#dom-img-src): *“The `alt`, **`src`**, … IDL attributes must ***reflect*** the respective content attributes of the same name.”* Now, *“reflect”* here is defined in, https://html.spec.whatwg.org/multipage/common-dom-interfaces.html#reflect – Jason Sparc Dec 10 '21 at 06:31
0

For relative source path

  function getImageURI(imagePath) {
      if (imagePath.indexOf('http') == 0) {
        return imagePath
      }
      var rootPath = window.location.protocol + "//" + window.location.host + "/";
      var path = window.location.pathname;
      if (path.indexOf("/") == 0) {
          path = path.substring(1);
      }
      path = path.split("/", 1);
      if (path != "") {
          rootPath = rootPath + path + "/";
      }
      return rootPath + imagePath;
  }