JQuery Get and Set Image Src Tutorial

JQuery Get and Set Image Src Tutorial

Hi Guys,

Today, I will learn you how to get and set image src in jquery. We will show easy example of jquery get and set image src.The attr() method to get and change the image source in jQuery.

Get Image Src

In this example,I will Use the below script to get image src.

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

In this example,I will Use the below script to set image src.

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

Now,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="https://1.bp.blogspot.com/-uVMRWbBdTYk/YIE9ZVl3fJI/AAAAAAAAGuo/UwQOuDB0uiQQrJC-ZP2VMEmkX8hJPDAfwCNcBGAsYHQ/s0/Laravel%2BCustom%2BENV%2BVariables%2BTut.png" width="100" id="first" alt="Blog Image"">
  </div>
  <div class="card">
    <img src="https://1.bp.blogspot.com/-avE6SJ3yKls/YIKfskcmf8I/AAAAAAAAGxU/qhoIZkLj5GU9L0dLXcKe4F5q1PZC6ZzWQCNcBGAsYHQ/s0/laravel-email-vali.png" width="100" id="second" alt="Blog Image">
  </div>
  <button type="type" class="btn">Get & Set image src</button>
</body>
</html>

It Will help you....