0

I want to get all the absolute urls of a website's images to display them, but I need the absolute url of a $('img').

I tried:

$('img').attr('src') 

but it only returned relative urls of a single one, I am using map to solve the problem of multiple images but still. How do I get the absolute url?

zardilior
  • 2,556
  • 23
  • 29

2 Answers2

4

Use .prop instead of .attr. This accesses the dynamic property, which is after canonicalization, rather than the static DOM attribute.

alert($('img').prop('src'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="placeholder.jpg"/>

See .prop() vs .attr()

Community
  • 1
  • 1
Barmar
  • 669,327
  • 51
  • 454
  • 560
1

This should give the absolute url for the first picture, of course you can loop through all of them:

$('img')[0].src

for (var i = 0; i<$('img').length;i++) {
alert($('img')[i].src)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="http://placekitten.com.s3.amazonaws.com/homepage-samples/408/287.jpg"/>
<img src="http://placekitten.com.s3.amazonaws.com/homepage-samples/200/140.jpg"/>
baao
  • 67,185
  • 15
  • 124
  • 181
  • Your answer is not bad but i needed to get absolutes from relatives in you example you are using absolute urls i mean what should i do for a src='../whatever.jpg' without going through string concatenation etc. Thnx for taking the time anyway – zardilior Dec 20 '14 at 01:05
  • Don't mind, but you will get absolute urls with src, no matter what the link is – baao Dec 20 '14 at 01:06
  • oh then thanks a lot for your answer. I should have tried it in the console. – zardilior Dec 21 '14 at 22:37