jQuery code to get absolute Image Path

It is a common practice to use relative path for images used in web application. The advantage of using relative path is that it can be easily migrated. One can easily migrate the web application from one domain to another without changing path of the images. But there can be a certain situations where you need to fetch the absolute path of the image from a relative path image. For example, while sending images url to other websites.

In today's post you will see jQuery code to find out the absolute path of any image which has relative path as source.

A relative path is a way to specify the location of a directory relative to another directory. For example, suppose your documents are in C:\Sample\Documents and your index is in C:\Sample\Index. The absolute path for the documents would be C:\Sample\Documents. The relative path from C:\Sample\Index to C:\Sample\Documents would be ..\Documents.

Below image tag is an example of relative path used as source.
<img id='imgLogo' src='/img/logo.png' />
One way to form absolute path is to add website URL to relative path of the image. But that's kind of hard-coding stuff which you should ignore.

When you are using jQuery, you can easily get the absolute path of the image using 'src' attribute. With jQuery 1.6 or higher version, a new method called 'prop()' was introduced. So using prop(), one can get value of src.
  var absPath = $('#imgLogo').prop('src');
But surprisingly attr() method will not return absolute path. It will return same value which is assigned to the src attribute.
  var absPath = $('#imgLogo').attr('src');
Try out yourself... Need to find out answer myself!!! If you have then please share.

Feel free to contact me for any help related to jQuery, I will gladly help you.

Nothing shocks me, I'm a Software Engineer. And I am not young enough to know everything. I live in World Wide Web and from there take care of this website. This website communicates about my work, learning and experience. I believe life is short, and it is for loving, sharing, learning and connecting. So lets connect..