Working Ninja
2017-07-19T10:46:37
Fire jQuery Event On Element Created After DOM Loaded

Let's say you add an element to the DOM via jQuery:

$("<button class="delete">Delete</button>").appendTo("foo");

And want to later remove it via a jQuery event. Calling $('.delete').on('click') will not fire the event. This is because .on() only looks for elements that were loaded initially with the DOM. To resolve you can use .live() for older version of jQuery or if you're using later versions of jQuery (1.7+), the following:

$(document).on("click", ".delete", function() { ... });

Since "document" existed when the DOM loaded a click on it will fire an event. Furthermore, since we specified the ".delete" CSS class for the selector arguement for the .on() event, the event will search through its descendents to find any elements with the ".delete" CSS class and execute our function.

Sources:
https://stackoverflow.com/questions/4900802/jquery-click-not-working-after-adding-element-to-the-dom
http://api.jquery.com/on/