Categories
JavaScript Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.