15

An HTMLImageElement has a currentSrc property so we can get the current source of an img element. Useful when defining multiple possible sources with srcset.

There seems to be no equivalent for an HTMLPictureElement.

Is there another way we can find the current source of a picture element with Javascript?

Colin Meinke
  • 173
  • 1
  • 1
  • 7
  • 3
    picture is only a container element to provide different sources for an image element inside the picture container - so I would assume that `currentSrc` of the `img` element works the same way here …? – CBroe Jan 20 '17 at 11:37
  • @CBroe that would make sense, do you know of any documentation that explains this? – Colin Meinke Jan 20 '17 at 11:48
  • @CBroe you're absolutely right. Thanks! – Colin Meinke Jan 20 '17 at 11:55

2 Answers2

34

You can access the currentSrc of the img element within a picture element to get the applied image.

In the demo below (if you're on a desktop with your browser full-width) the currentSrc will be the http://placehold.it/600x100 image.

window.onload = function() {
  const picture = document.getElementById('pictureEl');
  const currentSource = document.getElementById('currentSource');
  currentSource.innerText = picture.querySelector('img').currentSrc;
}
<picture id="pictureEl">
 <source srcset="http://placehold.it/600x100?text=Source" media="(min-width: 300px)">
 <img src="http://placehold.it/300x100?text=Img">
</picture>
<div id="currentSource"></div>
Brett DeWoody
  • 59,771
  • 29
  • 135
  • 184
0

Use this to get source of image.

function getCurrentSrc(element, cb){
    var getSrc;
    if(!window.HTMLPictureElement){
        if(window.respimage){
            respimage({elements: [element]});
        } else if(window.picturefill){
            picturefill({elements: [element]});
        }
        cb(element.src);
        return;
    }

    getSrc = function(){
        element.removeEventListener('load', getSrc);
        element.removeEventListener('error', getSrc);
        cb(element.currentSrc);
    };

    element.addEventListener('load', getSrc);
    element.addEventListener('error', getSrc);
    if(element.complete){
        getSrc();
    }
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Hiren Jungi
  • 854
  • 8
  • 20