You can use Mutation Events but the events have been marked as deprecated in the DOM Events specification, as the API's design is flawed.
The MutationEvent interface was introduced in DOM Level 2 Events, but has not yet been completely and interoperably implemented across user agents. In addition, there have been critiques that the interface, as designed, introduces a performance and implementation challenge. DOM4 provides a new mechanism using a MutationObserver interface which addresses the use cases that mutation events solve, but in a more performant manner. Thus, this specification describes mutation events for reference and completeness of legacy behavior, but deprecates the use of the MutationEvent interface.
One simple option is using .trigger()
method:
var $div = $(div).on('appendedToDOM', function() {
console.log('appended');
});
// ...
$div.appendTo('body').trigger('appendedToDOM');
You can also create a helper function that appends the element and triggers a custom event:
function append(elem, target, cEvent) {
if (typeof target === 'undefined') var target = document.body;
if (typeof cEvent === 'undefined') var cEvent = 'appendedToDOM';
$(elem).appendTo(target).trigger(cEvent);
}
// Usage
append(element [, targetElement] [, customEvent]);