jQuery Get Image Src and Set Image Src

jQuery Get Image Src and Set Image Src

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

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

jQuery Get Image Src

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

Example : jQuery Get Image Src

<html>
   <head>
      <title> jQuery Get Image Src </title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      <script>
         $(document).ready(function() {
            alert($('#myimg').attr('src'));
         });
      </script>
   </head>
   <body>
      <img src="/green/image.png" id="myimg">
   </body>
</html>

jQuery Set Image Src

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

Example : jQuery Set Image Src

<!DOCTYPE html>
 <html lang="en">
   <head>
   <meta charset="utf-8">
   <title>jQuery Change Image Source on Click</title>
   <style>
    .card{ margin: 30px; }
   </style> 
   <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
   <script>
    $(document).ready(function(){
     $("img").click(function(){
      // Change src attribute of image 
      $(this).attr("src", "images/card-front.jpg");
     });
   });
 </script>
 </head> 
<body>
 <div class="card">
  <img src="images/card-back.jpg" alt="Card">
 </div>
</body>
</html>