JQuery Get and Set Image Src Example Tutorial
Hi Guys,
Today, I will example 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="/upload/blog/1604552924_reactnaticematirailbootam.png" width="100" id="first" alt="Blog Image"">
</div>
<div class="card">
<img src="/upload/blog/1604121356_reactmatimage.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....
- How to Show Loading Spinner in JQuery?
- How to Create Ajax Submit Form Using jQuery?
- How To Get Current Page URL, Path, Host and hash using jQuery?
- How To Get, Set and Delete Div Background Image jQuery?
- JQuery Remove All Unwanted Whitespace From String Example
- Body Background Video Using Vide Jquery Example
- JQuery UI Autocomplete Example
- JQuery Split String By Comma Into Array Example