Change Images

JavaScript can change attributes other than innerHTML.

Try this example, and scroll down to the light bulbs:
W3Schools example changing light bulb images

You can change the src attribute of an image to change what picture is displayed:

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

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

(This example only works if you have picture files with those names on your website)

Things to notice in that example:

  • The <img> element has an id attribute (“animal”)
  • The JavaScript code (inside <script> tags) first creates an object to represent that picture (named “pic”) using getElementById()
  • pic.src = “dog.png” changes the image file that’s displayed in the “animal” image element.