I would say there are two reasons why this doesn't really exist.
- DOM modification events are not widely supported. You could listen for
DOMSubtreeModified
in Chrome and FF, but not in IE and Opera.
- Checking every DOM event against a selector would be very costly.
.live/.delegate
is already pretty inefficient of a strategy.
To help picture 2, imagine that 1 isn't a problem and we can capture any time an element is added to the DOM. When this happens, we need to evaluate the new element and its children against "#myTable tr"
. This will significantly increase the amount of non-native code executing with every DOM change in scope, really slowing things down.
The best strategy is to add your desired jQuery changes to the code that would be inserting the <tr>
UPDATE If you have no choice and only have to support Chrome and FF, there is one solution I can think of. Obviously, it will not be fast and you can improve your performance through specificity:
$.fn.elementInserted = function(pattern, fn) {
return this.bind('DOMNodeInserted', function(event) {
if (event.target.nodeType != 1) return;
$(event.target).filter(pattern).each(fn);
});
};
/* SLOW */ $(document).elementInserted('#myTable tr', function(){$(this).attr('hello', 'world');});
/* FASTER */ $('#myTable').elementInserted('tr', function(){$(this).attr('hello', 'world');});
See an example here: http://jsfiddle.net/vCZHQ/
You could theoretically check if the table has changed in IE by doing a timeout:
var oldEls = $('#myTable tr');
setInterval(function() {
var newEls = $('#myTable tr');
if(oldEls.length < newEls.length) {
/* Do code here to figure out who is new and apply changes. */
}
oldEls = newEls;
}, 50);
That said, this will have a slight delay and really drain a laptop's battery.