Most practical solution
You can hook into the DOMNodeInserted
event on document
to detect the changes, and use .is
to check if they match the selector of your choice.
$(function() {
var selector = "whatever";
$(document).on('DOMNodeInserted', function(e) {
if ($(e.srcElement || e.target).is(selector)) {
alert("Matching element inserted!");
}
});
});
See it in action.
Compatibility and alternatives
This approach is convenient, but it does have two drawbacks:
- The
DOMNodeInserted
event is deprecated.
- It does not work on IE < 9, and cannot be made to work.
As regards the first, I wouldn't consider this an issue. It may be deprecated, but as long as there is no other alternative I really don't think any browser vendor would pull this functionality. Maybe in five years or so this will become a practical issue, but since the code is 10 lines or so total it will surely be easy to update it to work with the latest standard.
For IE compatibility, the sad truth is that you cannot do anything directly. However, you can resort to verbose, horrible hacks that do provide results by modifying the prototypes of DOM elements. See an example tailored to work on IE8.
Sadly, there are multiple issues with this approach:
- You need to fish out all the methods that can result in the DOM being modified (or at least, all of those you will be using) and weave them into the solution. In the future you will be obliged to check if new DOM mutation methods are added and keep up with supporting them.
- You need to be extra careful to provide correct replacements for the methods, for all browsers that you choose to target with this (if more than one).
- Extending the DOM (in general) can be problematic. If you thought this specific method of extension is bad, consider that IE7 does not support it and on that browser you 'd have to replace methods on all elements in the DOM to make sure you hook into every possible modification.
- Specifically, you cannot target all current browsers with just this code (e.g. Chrome defines these methods on
Node.prototype
, not on Element.prototype
). Targeting future browsers should not be mentioned even if joking.
Finally, you can always decide to use polling to detect changes, as Anthony explains in his answer.
Related resources