Home > Article > Web Front-end > How do you dynamically update the source URL of an image tag using JavaScript?
Change the Source URL of an Image Using JavaScript
To dynamically update the source URL of an image tag using JavaScript, it's important to ensure proper handling of event listeners and element identification.
Solution:
Add an ID to the img Tag:
Assign a unique ID to the img tag. This will help you target it specifically in the JavaScript code.
<code class="html"><img src="../template/edit.png" id="edit-save" alt="Edit" /></code>
Access the Image Element:
Use the document.getElementById() method to obtain a reference to the img element.
<code class="javascript">var editSave = document.getElementById("edit-save");</code>
Change the src Attribute:
Once you have the image element reference, you can modify its src attribute to update the image source.
<code class="javascript">editSave.src = "../template/save.png";</code>
Example:
In your provided code, add an ID as follows:
<code class="html"><a href="#" onclick="edit()"><img src="../template/edit.png" id="edit-save" alt="Edit" /></a></code>
Then, modify your JavaScript function:
<code class="javascript">function edit() { var editSave = document.getElementById("edit-save"); editSave.src = "../template/save.png"; }</code>
With this approach, the image source will be updated correctly with a single click on the image.
The above is the detailed content of How do you dynamically update the source URL of an image tag using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!