Home >Web Front-end >JS Tutorial >How to Dynamically Change the `src` Attribute of an Image Tag Using JavaScript?
Query:
How can I modify the src attribute of an img tag dynamically using JavaScript?
Example:
Consider an img tag with an initial src path of "../template/edit.png". The goal is to change this path to "../template/save.png" when the tag is clicked.
HTML Code with ID:
<code class="html"><a href="#" onclick="edit()"><img src="../template/edit.png" id="edit-save" alt="Edit" /></a></code>
JavaScript Code with getElementById:
<code class="javascript">document.getElementById("edit-save").src = "../template/save.png";</code>
Explanation:
By assigning an id to the img tag, you can easily select and manipulate it using JavaScript. The getElementById method returns the HTML element with the specified id. You can then access its src property and assign the new source path directly.
Note:
This approach avoids the need for multiple clicks to change the source as seen in your previous attempt.
The above is the detailed content of How to Dynamically Change the `src` Attribute of an Image Tag Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!