jQuery dynamically set/change and get image src; Through this tutorial, i am going to show you how to get and set the image src in jQuery by id, name and tag.
How to Set and Get Image src in jQuery
Use the jQuery attr()
method to get and set/change the image src in jQuery:
- jQuery Get Image src Dynamically
- jQuery Set Image src Dynamically
- Example for jQuery Dynamically Set and Get Image src
jQuery Get Image src Dynamically
The following jQuery script code will get image src; as shown below:
$(document).ready(function() { $('.btn').click(function(){ $imgsrc = $('img').attr('src'); alert($imgsrc); }); });
jQuery Set Image src Dynamically
The following jQuery script code will get image src; as shown below:
$(document).ready(function() { $('.btn').click(function(){ $("img").attr("src",'test.png'); }); });
Example for jQuery Dynamically Set and Get Image src
See the following example for how to set and get image src in jQuery using attr(); as shown below:
<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="http://laratutorials.com/wp-content/uploads/2021/04/jQuery-Remove-All-Space-From-String.jpg" width="100" id="first" alt="Poker Card"> </div> <div class="card"> <img src="http://laratutorials.com/wp-content/uploads/2021/04/jQuery-Remove-All-Space-From-String.jpg" width="100" id="second" alt="Poker Card"> </div> <button type="type" class="btn">Get & Set image src</button> </body> </html>
Conclusion
jQuery dynamically set and get image src; Through this tutorial,You have learned how to get and set the image src in jQuery.
Recommended jQuery Tutorial
Recommended:-jQuery setInterval and setTimeout
Recommended:-jQuery Select Multiple Classes
Recommended:-jQuery Registration Form validation using Validator
Recommended:-jQuery Form Validation Custom Error Message
Recommended:-jQuery Get Set and Delete Div Background Image
Recommended:-jQuery Get Current Page URL, Path, Host and hash
Recommended:-jQuery Remove Duplicate Objects from Array
Recommended:-jQuery Convert Image into base64 String
Recommended:-jQuery Range UI Slider With Tooltip, Labels
Recommended:-jQuery Reload or Refresh Page Automatically
Recommended:-jQuery Remove Elements From array and Object
Recommended:-jQuery Remove All Space From String