Change Image with JavaScript Summary

JavaScript can replace an image after a page loads. It does this by changing the image file named in the HTML src attribute.

This is useful when a gallery moves to the next photo, a product displays another color, or an icon changes to show a new state.

How to Change an Image with JavaScript

First, the HTML needs an image for JavaScript to find. This image has an ID attribute named photo.

<img id="photo" src="first-image.jpg" alt="A mountain at sunrise">

JavaScript can replace the image with one line:

document.querySelector('#photo').src = 'second-image.jpg';

When this code runs, the browser stops displaying first-image.jpg and displays second-image.jpg instead.

Find the Image

The first part finds the image that JavaScript will change:

document.querySelector('#photo')

querySelector() finds an HTML element using a CSS selector. The #photo selector finds the element with id="photo".

Change the Image Source

The second part gives the image a new source:

.src = 'second-image.jpg';

The src property represents the image’s src attribute. The equals sign gives it a new image path. The path goes inside quotation marks.

The new path must point to an image that exists. If the filename or folder is wrong, the browser will show a broken image instead.

Remember the Alt Text

An image’s alt text describes the image for people who cannot see it. If the new image communicates something different, its alt text should change too.

document.querySelector('#photo').alt = 'A beach at sunset';

This is a separate change. The main image example needs only the line that changes src.

When Websites Change Images

Changing an image lets one part of a page display different visual information without loading a new page.

  • Move through photos in a gallery.
  • Show a different product color.
  • Replace a play icon with a pause icon.
  • Display a new picture after someone makes a choice.

Try Changing the Image

The sandbox begins with an image path that does not exist. Select Update Code, and JavaScript will replace it with the correct path to the AI Coding Educator icon.

To see why the exact path matters, change aice-icon.png to different-icon.png and update the code again. The image will not load because that file does not exist.

Interactive Demo

First image New image

Code Sandbox

AI Tutor