user2417713 user2417713 - 2 years ago 152
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.

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download