user2417713 user2417713 - 9 months ago 64
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(){

Please advise.


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:


Codepen Example