Arthur Tarasov Arthur Tarasov - 1 year ago 53
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
is of a
? Is there any way to make the following work:

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

Answer Source

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.

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