Change Images

Changing Images (src)
JavaScript can change the picture shown in an <img> element by updating its src attribute.

Example

<img id="animal" src="cat.png">

<script>
let pic = document.getElementById("animal");
pic.src = "dog.png";   // switch image
</script>

(Make sure the image files exist on your site.)

You can trigger the change inside a function:

<img id="animal" src="cat.png">
<button onclick="switchPic()">Switch</button>

<script>
let pic = document.getElementById("animal");
function switchPic(){
  pic.src = "dog.png";
}
</script>

Natural Next Questions
You might be wondering:

More on changing HTML attributes with JavaScript:

W3Schools – JavaScript HTML DOM (Change Attributes)


This page was tweaked with the help of ChatGPT. But the original was pretty good already. 😉