Arthur Tarasov Arthur Tarasov - 3 months ago 7
jQuery Question

How to bind an event to a dynamically created element within another dynamically created element?

Binding events to a dynamically created element that has a static ancestor is fairly easy using jQuery, as demonstrated in this answer:

$(staticAncestors).on(eventName, dynamicChild, function() {});


But what if the
dynamicChild
is of a
dynamicAncestor
? Is there any way to make the following work:

$(dynamicAncestors).on(eventName, dynamicChild, function() {});

Answer

When using on, you should bind to the nearest static parent element. In some cases, that may be body:

$('body').on(eventName, 'dynamic-element', function() {  });

Binding all events to body is generally bad practice though, so it's difficult to answer your question more thoroughly without seeing your DOM. But binding to the nearest static parent will work for what you're trying to achieve.