In the previous tutorial, we changed the innerHTML of an element by using the getElementById() method. This allowed us to change the text in a paragraph when we clicked on the paragraph. That is, the text “Click here” was changed to “You clicked here” once it had been clicked.
We will use the same method, but we will change the source of an image instead. This means that we will have one image on our web page and when the user clicks on that image it will be swapped with another image. In the example in the video and sample code below, an orange circle will be replaced with a blue circle when we click on it.
Watch the video below and then scroll down to see the sample code.
The sample code below shows how to use the getElementById() method to swap an image in a HTML web page. If you are not already familiar with how to include an image in a web page, then you will see how to do that using the img src tag. However, it is recommended that you get familiar with HTML before going much further.
Note that the sample code above won’t work properly unless you have images orange.png and blue.png in the same folder/directory as your HTML file. You can try the code out yourself and make your own images instead.