How to set an image’s src attribute to another image URL with JavaScript?

Sometimes, we want to set an image’s src attribute to another image URL with JavaScript.

In this article, we’ll look at how to set an image’s src attribute to another image URL with JavaScript.

How to set an image’s src attribute to another image URL with JavaScript?

To set an image’s src attribute to another image URL with JavaScript, we can set the src property of the img element.

For instance, we write:

<img src='https://picsum.photos/50/50'>

to add an img element.

Then we write:

const img = document.querySelector('img')
img.src = 'https://picsum.photos/500/500'

to select the img element with document.querySelector.

And then we set the img.src property with the new image URL.

Now the new image is displayed on screen.

Conclusion

To set an image’s src attribute to another image URL with JavaScript, we can set the src property of the img element.