'How to add a picture element in javascript with multiple source tags

I am trying to do this

<picture>
  <source srcset="img/awesomeWebPImage.webp" type="image/webp">
  <source srcset="img/creakyOldJPEG.jpg" type="image/jpeg"> 
  <img src="img/creakyOldJPEG.jpg" alt="Alt Text!">
</picture>

but in javascript like this

  const image = document.createElement('picture');
  image.className = 'object-img';
  image.src = DBHelper.imageUrlForObject(object);
  image.setAttribute("srcset",`${image.src}_small_1x.jpg 550w, ${image.src}_medium_1x.jpg 800w,
  ${image.src}_large_1x.jpg 1600w`);
  image.setAttribute("srcset",`${image.src}_small_1x.webp 550w, ${image.src}_medium_1x.webp 800w,
  ${image.src}_large_1x.webp 1600w"`);
  image.setAttribute("alt",`Image of ${object.name}`);
  image.alt = `Image of ${object.name}`;
  li.append(image);

This doesn't work, I am thinking because I need to add an img tag in there somehow?



Solution 1:[1]

var pcr = document.createElement("PICTURE");
var sc1 = document.createElement("SOURCE");
var sc2 = document.createElement("SOURCE");
var img = document.createElement("IMG");

pcr.srcset="img/awesomeWebPImage.webp";
pcr.type="image/webp";
sc1.srcset="img/creakyOldJPEG.jpg";
sc1.type="image/jpeg";
sc2.srcset="img/creakyOldJPEG.jpg";
sc2.type="image/jpeg";
img.src="img/creakyOldJPEG.jpg";
img.alt="Alt Text!";

pcr.appendChild(sc1);
pcr.appendChild(sc2);
pcr.appendChild(img);

Solution 2:[2]

var pcr = document.createElement("PICTURE");
var sc1 = document.createElement("SOURCE");
var sc2 = document.createElement("SOURCE");
var img = document.createElement("IMG");

pcr.srcset="img/awesomeWebPImage.webp";
pcr.type="image/webp";
sc1.srcset="img/creakyOldJPEG.jpg";
sc1.type="image/jpeg";
sc2.srcset="img/creakyOldJPEG.jpg";
sc2.type="image/jpeg";
img.alt="Alt Text!";

pcr.appendChild(sc1);
pcr.appendChild(sc2);
pcr.appendChild(img);

Do not set src of img tag. If you will set src it will load image right away. So you will load webp and jpg.

fall back will work based on source type.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 malik kurosaki
Solution 2 Dimash