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:SampleDocuments and your index is in C:SampleIndex. The absolute path for the documents would be C:SampleDocuments. The relative path from C:SampleIndex to C:SampleDocuments 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.

$(document).ready(function(){
  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.

$(document).ready(function(){
  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.



Responsive Menu
Add more content here...