简体   繁体   中英

javascript get the full src url for an img element

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;

See MDN documentation for HTMLImageElement.src .

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM