Home >Web Front-end >JS Tutorial >How do I dynamically update the `src` attribute of an image using JavaScript?

How do I dynamically update the `src` attribute of an image using JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-11-03 22:11:31688browse

How do I dynamically update the `src` attribute of an image using JavaScript?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn