In JavaScript/jQuery, if I want to have a function that can run on an element that has been appended to the DOM, it has to be created after the element has been appended to the DOM. How can I do this? I heard one can do this with the jQuery .on() function, but I’m not quite sure how.
HTML:
<span>Hello Stackoverflow</span>
JavaScript:
$("span").click(function () {
addMyElement();
});
$("p").click(function () {
removeMyElement(this);
});
function addMyElement() {
$("<p>Hello World</p>").appendTo("body");
}
function removeMyElement(myElement) {
$(myElement).remove();
}
Example on jsFiddle.net.
This is called delegated-events approach and it works as follows:
Instead of
bodyyou can use any parent element ofp.DEMO: http://jsfiddle.net/wWXrK/6/