To set an img element’s src attribute with a JavaScript function’s return value, we can select the img element and set its src
property.
For instance, we write:
<img />
to add an img element.
Then we write:
const getImgSrc = () => 'https://picsum.photos/200/300'
const img = document.querySelector('img')
img.src = getImgSrc()
to define the getImgSrc
function to return the image URL string.
Then we select the img element with querySelector
.
And then we set img.src
to the value returned by getImgSrc
.