JQuery Get and Set Image Src Example Tutorial

Jquery

Nicesnippets

240

15-11-2020


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="https://www.nicesnippets.com/upload/blog/1604552924_reactnaticematirailbootam.png" width="100" id="first" alt="Blog Image"">

</div>

<div class="card">

<img src="https://www.nicesnippets.com/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....


Recommended Posts