Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an img url using jQuery?

Is it possible to get the actual URL (as opposed to the src attribute value) of an image within the current DOM using jQuery or JavaScript?

i.e. retrieve "example.com/foo.jpg" as opposed to "foo.jpg" (taking <base> elements into account)

What about any other interesting properties such as the mime type, file size or, best of all, the actual binary data?

like image 358
stovroz Avatar asked Apr 25 '09 13:04

stovroz


2 Answers

I wonder if jQuery is using .getAttribute() - using .src always seems to give the absolute URL:

<img src="foo.jpg" id="i">

<script>
var img = document.getElementById('i');

alert(img.getAttribute('src')); // foo.jpg
alert(img.src);                 // http://..../foo.jpg
</script>

To get the rest of the information, could you use an AJAX request and look at the header & data sent?

like image 161
Greg Avatar answered Oct 14 '22 14:10

Greg


$(you IMG selector).attr('src');

for instance, if we have an <img src='bla-bla.jpg' id='my_img'>

then we'll do:

$('#my_img').attr('src');
like image 34
user149662 Avatar answered Oct 14 '22 15:10

user149662