Home >Web Front-end >JS Tutorial >How to Dynamically Change the `src` Attribute of an Image Tag Using JavaScript?

How to Dynamically Change the `src` Attribute of an Image Tag Using JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-11-02 13:18:021035browse

How to Dynamically Change the `src` Attribute of an Image Tag Using JavaScript?

Changing the Source Attribute of an Image Tag via 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!

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