136

I hope when I click the button, I can get the specific img src and show the img src in the div class img-block block.

HTML

<button class="button">Click</button>
<div class="img1">
    <img src="img.jpg" alt="">
</div>

<div class="img-block"></div>

CSS

.img-block{
    position: absolute;
    top:10%;
    right:10%;
    background-color: red;
    width: 500px;
    height: 500px;
}
.img1 img{
    width: 200px;
}

JS

$('.button').click(function(){
  var images = $('.img1 img').attr(src);
  alert(images);      
});

But now I face the problem is to get the img src.
So I use alert to make the test, the result is it alert nothing.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Chen-Tai
  • 3,435
  • 3
  • 21
  • 34

8 Answers8

264

src should be in quotes:

$('.img1 img').attr('src');
Stuart Kershaw
  • 16,831
  • 6
  • 37
  • 48
14

for full url use

$('#imageContainerId').prop('src')

for relative image url use

$('#imageContainerId').attr('src')

function showImgUrl(){
  console.log('for full image url ' + $('#imageId').prop('src') );
  console.log('for relative image url ' + $('#imageId').attr('src'));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id='imageId' src='images/image1.jpg' height='50px' width='50px'/>

<input type='button' onclick='showImgUrl()' value='click to see the url of the img' />
noone
  • 6,168
  • 2
  • 42
  • 51
8

You may find likr

$('.class').find('tag').attr('src');
parth-BSP
  • 124
  • 1
  • 2
3

When dealing with the HTML DOM (ie. this), the array selector [0] must be used to retrieve the jQuery element from the Javascript array.

$(this)[0].getAttribute('src');
Jacob
  • 187
  • 1
  • 7
3

html :

<img id="img_path_" width="24" height="24" src=".." class="img-fluid" alt=“">

js:

$('#img_path_').attr('src')
Ayse
  • 576
  • 4
  • 13
2

In my case this format worked on latest version of jQuery:

$('img#post_image_preview').src;
Nezir
  • 6,727
  • 12
  • 54
  • 78
1

This is what you need

 $('img').context.currentSrc
suzuko
  • 11
  • 1
0
jQuery(document).ready(function($){
                $('body').on('click','.button',function(){              
                    var imgsrc=$('.img1 img').attr('src');              
                    $(".img-block").append(imgsrc);
                })
            });