How to set an img element’s src attribute with a JavaScript function’s return value?

Sometimes, we want to set an img element’s src attribute with a JavaScript function’s return value.

In this article, we’ll look at how to set an img element’s src attribute with a JavaScript function’s return value.

How to set an img element’s src attribute with a JavaScript function’s return value?

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.

Conclusion

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.