Changing the image source using jQuery

Let's discuss, how to change the source of the image from one image to another using jQuery?
Submitted by Pratishtha Saxena, on August 26, 2022

There are various instances when there is a need to change the image when needed. This has to be dynamic as it generally depends on some click events or other events. Therefore, it can be handled by jQuery. There can be different situations when the image needs to be swapped with a different one to meet the requirement. Over here, we'll be discussing how to perform this task with a click of a button using jQuery.

This thing can be achieved by again using one of the most important methods of jQuery, i.e., the .attr() method. It is a very useful method, which helps either to set or return the attributes of the selected element.


Different attributes can be specified over here and set them. Since we need to change the source of the image, the attribute we need to specify here is the src. The address of the new image that has to be swapped with the old one is given in the src (source) attribute.

Let's take a look at the following given example.

Example to change the image source using jQuery

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src=""></script>
    <h2>Change The Img Source On Click Using jQuery</h2>
    <p>When the following button is clicked, the image gets changed.</p>
    <img id="myImg" src="">
    <button type="button" id="button1">Get Flower Img</button>
  <script type="text/javascript">


Example: Changing the image source

All jQuery Examples

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.