jQuery Replace Image Tutorial (Part 1)
We already learned some basic knowledge of jQuery codes in previous tutorials. It is time to play something interesting with jQuery codes. In this tutorial, the image will be replaced or changed to another image when click on it.
Set Attribute Value of Selected Element with attr() Method
The jQuery attr() method can set the attribute value of selected element. The basic syntax of jQuery attr() Method is shown in the diagram below:

Since the jQuery attr() method can set the attribute value of selected element, we can use this concept to replace the image.
Goal of jQuery Tutorial
In this jQuery tutorial, the boat image will be changed when the mouse pointer click on it.

This is part of the HTML codes of the boat image.
- The id attribute of the boat image is "boat".
- The src attribute of the boat image is "boat.png".
<img src="boat.png" alt="boat" id="boat" width="203" height="190" />
Let's recall what we learned before:
- The id of the boat layer will display when click on it.
$("#boat").click(function() {
elementName = this.id;
$("#outputText").text("The name is: " + elementName);
}
Return Attribute Value of Selected Element with attr() Method
Let's learn something new with the jQuery attr() method. The jQuery attr() method also allows to return the value of attribute. The syntax is ahown as below:

Example:
The "src" attribute of selected element (i.e. boat.png) will be displayed when click on it.
$("#boat").click(function() {
var srcName = $(this).attr("src");
$("#outputText").text("The name is: " + srcName);
}
We already got enough knowledge. It's time to see how to replace images with jQuery codes.
