There are two ways to do this ...
Firstly, you can take a snapshot of dom ( var snap = document.body ), compare it with dom 100ms later, and then reset snap to body again. I will allow you to be creative in comparing them: iteration seems to be the general answer. This is not very.
Another option is to have a special function in any functions you create that add / remove elements in your application. This function will iterate over only the elements that you add (or destroy), and look for a match.
/* Shim matchesSelector */ if (!Element.prototype.matchesSelector) { Element.prototype.matchesSelector = Element.prototype.matches || Element.prototype.webkitMatchesSelector || Element.prototype.mozMatchesSelector || Element.prototype.msMatchesSelector || Element.prototype.oMatchesSelector; } function addingToDom(elm){ /* Whichever method you want to use to map selectors to functions */ var callbacks = array(['.class', fn-reference1], ['#id', fn-reference2], ['div', fn-reference3]); /* go through all the elements you're adding */ for (var i = 0; i<elm.length; ++i){ /* go through all the selectors you're matching against */ for (var k = 0; k<callbacks.length ++k){ if(elm[i].matchesSelector(callbacks[k][0])){ /* call function with element passed as parameter */ callbacks[k][1](elm[i]); } } } }
It may not be perfect, but it should give you an idea of where to start. Call this function (addToDom) by passing the elements you just added as an argument. Create a similar function to delete items (or the same function, but set up a separate callback array).
This is an extrapolation of the current (large and dirty) code that I use to test some ideas. I checked the match selector even like ie7 with this pad, and it seems to work great!
I considered, but did not consider, the possibility that the element has some parameter that can be set as a function called upon addition, passing itself as a parameter. BUT, perhaps far-fetched.
source share