0

I am not able to get the src attribute of the image that i created using the .append method in Jquery. I am able to get src when i type the element in html file but not when i append it. In short the alert method at the end of below code doesnt give the src of the img.

HTML:

<button onclick="createlm()">click</button>
<div class="row"></div>

JQUERY:

//function to append img element..

function createlm(){
    $(".row").append("<img src='image/Chrysanthemum.jpg' width='100px' height='100px'>");
}; 

//function to get src attribute

$(window).load(function(){
    $(".row>img").click(function(){
        var imgsrc = $(this).attr("src");
        alert(imgsrc);
    });
});
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
Shinaj
  • 105
  • 6
  • Make sure that your selector is correct because it can return more than one image, if you append more than once. – Amauri Sep 28 '17 at 18:07
  • If its possible use console.log(imgsrc); to check your object at developers tool – Amauri Sep 28 '17 at 18:09

1 Answers1

0

Your function to get src attribute is added to all .row>img elements before you have a chance to click the button create an image.

You could reattach the click event after the image is added, but a better way might be to attach the listener to some parent element that will always exist. You can do that like this:

$('.row').on('click', 'img', function() {
    var imgsrc = $(this).attr("src");
    alert(imgsrc);
});

Even if images are added after this event handler, the handler will still execute.

arbuthnott
  • 3,819
  • 2
  • 8
  • 21