Reputation: 9386
I know I can get the src url of the first image on the page with this
var images = document.getElementsByTagName('img');
var image = images[0]; //get first img
var src = image.getAttribute('src');
But I have come accross the situation when the src url is:
//domain.com/img/icon.png
I was able to fix this by adding the line:
if (src.substring(0,2) == '//') src = 'http:'+src;
But then I ran into more problems. Like what if the url is:
'/img/icon.png'
or
'../img/icon.png'
And I don't know if there are still other edge cases I haven't yet found. Is there any way to query for the full url of the src?
Upvotes: 0
Views: 5491
Reputation: 11
Instead of using image.getAttribute('src')
which just gets the attribute, you should use image.src
which will return the full URL.
Source: http://www.w3schools.com/jsref/prop_img_src.asp
Upvotes: 1
Reputation: 238045
Yes. You should use the src
property rather than the src
attribute. This is normalized to include the base URL:
var src = image.src;
See MDN documentation for HTMLImageElement.src
.
Upvotes: 5