Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the current image source of a picture element

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?

like image 613
Colin Meinke Avatar asked Jan 20 '17 11:01

Colin Meinke


People also ask

How can I get the source of an image in HTML?

To use an image on a webpage, use the <img> tag. The tag allows you to add image source, alt, width, height, etc. The src is to add the image URL. The alt is the alternate text attribute, which is text that is visible when the image fails to load.

What is a picture element in an image?

A picture element (pixel) is the smallest area in an image that can be reproduced by the video signal.

What is currentSrc?

currentSrc lets you determine which image from the set of provided images was selected by the browser.

What is Srcset in html5?

srcset defines the set of images we will allow the browser to choose between, and what size each image is. Each set of image information is separated from the previous one by a comma.


1 Answers

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>
like image 198
Brett DeWoody Avatar answered Sep 28 '22 03:09

Brett DeWoody