Dynamically Updating Image Source using JavaScript
JavaScript offers a simple yet effective method to alter the src attribute of an img tag, enabling dynamic image manipulation. Consider the following HTML structure:
<code class="html"><img src="../template/edit.png" name="edit-save" alt="Edit" /></code>
Initially, the image displays "../template/edit.png". However, you wish to switch it to "../template/save.png" upon clicking. To achieve this, add an id attribute to the img tag, as seen below:
<code class="html"><a href="#" onclick="edit()"><img src="../template/edit.png" id="edit-save" alt="Edit" /></a></code>
In your edit() function, you can now effortlessly update the image source using the following code snippet:
<code class="javascript">var edit_save = document.getElementById("edit-save"); edit_save.src = "../template/save.png";</code>
This method allows for seamless image swapping without the need for excessive clicks.
The above is the detailed content of How do I dynamically update the `src` attribute of an image using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!