user2417713 user2417713 - 4 months ago 14
jQuery Question

Change img src created via appendTo

I have created a button via the appendTo function:

$('<span id="metroBtn" class="play_btns"><img src="pngs/metro.png"></span>').appendTo( '#cardSlots' );


I am trying to change the img src via the following, but it's not working:

$('#cardSlots').on('click', '#metroBtn', function(){
$(this).attr('src','pngs/new_img.png');
}


Please advise.

Answer

In your jquery, $(this) is referring to the element to which the click event is attached, which is the #metroBtn wrapper. You will need to target the img in order to change its source. You can do this with the find() method:

$(this).find('img').attr('src','pngs/new_img.png');

Codepen Example

Comments