Change an image using the Get Element By Id Method

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.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Changing an image once</title>
 <script type="text/javascript">
 
 /* In the previous tutorial, we changed the innerHTML of an element by using the getElementById() method
 We will use the same method, but we will change the source of an image instead.
 */ 
 
 function change(){
 var image = document.getElementById('circle');
 image.src = "blue.png";
 }
 
 
 
 </script>
 
</head>
<body>
 
<img src="orange.png" alt="Circle" id="circle" onclick="change();">
 
 
</body>
</html>

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.

Next tutorial: Swapping images back and forth using JavaScript