MutationObserver
Using MutationObserver is the currently recommended method, although browser support requires IE11+:
var target = document.getElementById('content');
var observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
for (var i = 0; i < mutation.addedNodes.length; i++) {
var addedNode = mutation.addedNodes[i];
if (addedNode.id == "myElement") {
alert("#myElement added!");
}
}
});
});
var config = {
attributes: true,
childList: true,
characterData: true
};
observer.observe(target, config);
Here is a working example
Mutation Events (deprecated)
This method is deprecated, but will offer browser support from IE9+:
This feature has been removed from the Web. Though some browsers may
still support it, it is in the process of being dropped. Do not use it
in old or new projects. Pages or Web apps using it may break at any
time.
(Above extract taken from here)
With Mutation Events there is an event called DOMNodeInserted
which you can listen out for, you can also specify the #myElement
selector to get the exact element(s) you want.
This example uses JQuery:
$(document).on('DOMNodeInserted', '#myElement', function(){
$("#myElement").attr("id", "new-id");
});
NOTE: document
should be replaced with what ever selector you need, the more you can limit the area the better.
Here is a working example (element added after 2 seconds)