Home > Web Front-end > JS Tutorial > How do you dynamically update the source URL of an image tag using JavaScript?

How do you dynamically update the source URL of an image tag using JavaScript?

Patricia Arquette
Release: 2024-10-31 05:25:30
Original
394 people have browsed it

How do you dynamically update the source URL of an image tag using JavaScript?

Change the Source URL of an Image Using JavaScript

To dynamically update the source URL of an image tag using JavaScript, it's important to ensure proper handling of event listeners and element identification.

Solution:

  1. Add an ID to the img Tag:
    Assign a unique ID to the img tag. This will help you target it specifically in the JavaScript code.

    <code class="html"><img src="../template/edit.png" id="edit-save" alt="Edit" /></code>
    Copy after login
  2. Access the Image Element:
    Use the document.getElementById() method to obtain a reference to the img element.

    <code class="javascript">var editSave = document.getElementById("edit-save");</code>
    Copy after login
  3. Change the src Attribute:
    Once you have the image element reference, you can modify its src attribute to update the image source.

    <code class="javascript">editSave.src = "../template/save.png";</code>
    Copy after login

Example:

In your provided code, add an ID as follows:

<code class="html"><a href="#" onclick="edit()"><img src="../template/edit.png" id="edit-save" alt="Edit" /></a></code>
Copy after login

Then, modify your JavaScript function:

<code class="javascript">function edit() {
    var editSave = document.getElementById("edit-save");
    editSave.src = "../template/save.png";
}</code>
Copy after login

With this approach, the image source will be updated correctly with a single click on the image.

The above is the detailed content of How do you dynamically update the source URL of an image tag 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