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?
Yes. You should use the src
property rather than the src
attribute . This is normalized to include the base URL:
var src = image.src;
Instead of using image.getAttribute('src')
which just gets the attribute, you should use image.src
which will return the full URL.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.