EN
JavaScript - change image src
3
points
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>