Home > Web Front-end > JS Tutorial > body text

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

Barbara Streisand
Release: 2024-11-03 22:11:31
Original
634 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template