How to get the image tag src and set the image tag src using jQuery

How to get the image tag src and set the image tag src using jQuery
In this article, you have learned how to get the image tag src and set the image tag src using jQuery attr() with example.

Overview

How to get the image src and set the image src using jQuery attr(). In this article, you will learn how to get and set the image src using jQuery.

The attr() method to get and change the image source in jQuery.

Get Image Src

Use the below script to get image src.

$(document).ready(function() {
 
    $('.btn').click(function(){
 
        $imgsrc = $('img').attr('src');
        alert($imgsrc);
 
    });
 
 });

Set the Image Src

Use the below script to set the image src.

$(document).ready(function() {
 
    $('.btn').click(function(){
 
       $("img").attr("src",'test.png');
 
    });
 
});

Let’s take an example

The following example will change the second image to the first image.

<html>
 
   <head>
 
      <title> How to get and set image src attribute example</title>
 
      <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>   
 
      <script>
 
         $(document).ready(function() {
 
            $('.btn').click(function(){
 
                $imgsrc = $('#first').attr('src');
                $("#second").attr("src",$imgsrc);
 
            });
 
         });
 
      </script>
      <style>
        .card{
            margin: 30px;
        }
     </style>
   </head>
 
   <body>
 
    <div class="card">
        <img src="//www.tutsmake.com/wp-content/uploads/2019/08/How-to-Encode-Decode-a-URL-Using-JavaScript.jpeg" width="100" id="first" alt="Poker Card">
    </div>
 
 
    <div class="card">
        <img src="//www.tutsmake.com/wp-content/uploads/2019/08/How-to-Download-Install-XAMPP-on-Windows.jpeg" width="100" id="second" alt="Poker Card">
    </div>
 
   <button type="type" class="btn">Get &amp; Set image src</button>
 
 
   </body>
 
</html>

In the above example, we have got the first image src and set the src to the second image.

Conclusion

In this article, you have learned how to get the image tag src and set the image tag src using jQuery attr() with example.

Suggest:

JavaScript Programming Tutorial Full Course for Beginners

Learn JavaScript - Become a Zero to Hero

Is jQuery Still Relevant in 2018?

Top 10 JavaScript Questions

E-Commerce JavaScript Tutorial - Shopping Cart from Scratch

JavaScript Substring Method in 5 Minutes