Languages
[Edit]
EN

JavaScript - change image src

3 points
Created by:
troya
692

In this article, we would like to show you how to change image src using JavaScript.

Quick solution:

var image = document.querySelector('#image');

image.src='path/to/new/image.png';

 

Practical example

In this example, we get the handle to the image using document.querySelector() and change its source using the src property.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <div>Just image:</div>
  <img id="image-1" src="https://dirask.com/static/bucket/1631898942509-VMYrnXyYZv--image.png" />
  <div>Image with changed src using JavaScript:</div>
  <img id="image-2" src="https://dirask.com/static/bucket/1631898942509-VMYrnXyYZv--image.png" />
  <script>

    var image = document.querySelector('#image-2');

    image.src = 'https://dirask.com/static/bucket/1574890428058-BZOQxN2D3p--image.png';

  </script>
</body>
</html>

 

References

  1. HTMLImageElement.src - Web APIs | MDN
  2. <img>: The Image Embed element - HTML: HyperText Markup Language | MDN

Alternative titles

  1. JavaScript - change image url
  2. JavaScript - reload image with new URL
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join