How To Get and Set JQuery Image Src Example

How To Get and Set JQuery Image Src Example


How To Get and Set JQuery Image Src

In This Article, we learned How To Get and Set JQuery Image Src using JQuery.

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

jQuery prop() Method: This method sets/returns properties and values of the matched elements. If this method is used to return the property value, it returns the value of the first selected element. If this method is used to set property values, it sets one or more property/value pairs for the set of selected elements.

set JQuery Images Src.

Use the below script to get image src.

1
2
3
4
5
6
7
8
9
10
$(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.

1
2
3
4
5
6
7
8
9
$(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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<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://www.freejquery.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="http://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.


 

Leave a Reply

Your email address will not be published. Required fields are marked *