Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
33
rated 0 times [  37] [ 4]  / answers: 1 / hits: 59823  / 15 Years ago, tue, march 16, 2010, 12:00:00

I need an efficient mechanism for detecting changes to the DOM. Preferably cross-browser, but if there's any efficient means which are not cross browser, I can implement these with a fail-safe cross browser method.



In particular, I need to detect changes that would affect the text on a page, so any new, removed or modified elements, or changes to inner text (innerHTML) would be required.



I don't have control over the changes being made (they could be due to 3rd party javascript includes, etc), so it can't be approached from this angle - I need to monitor for changes somehow.



Currently I've implemented a quick'n'dirty method which checks body.innerHTML.length at intervals. This won't of course detect changes which result in the same length being returned, but in this case is good enough - the chances of this happening are extremely slim, and in this project, failing to detect a change won't result in lost data.



The problem with body.innerHTML.length is that it's expensive. It can take between 1 and 5 milliseconds on a fast browser, and this can bog things down a lot - I'm also dealing with a large-ish number of iframes and it all adds up. I'm pretty sure the expensiveness of doing this is because the innerHTML text is not stored statically by browsers, and needs to be calculated from the DOM every time it is read.



The types of answers I am looking for are anything from the precise (for example event) to the good enough - perhaps something as quick'n'dirty as the innerHTML.length method, but that executes faster.



EDIT:
I should also point out that whilst it would be nice to detect the precise element that has been modified, it is not an absolute necessity - just the fact that there has been any change would be good enough. Hopefully this broadens people's responses. I'm going to investigate Mutation Events, but I still need a fallback for IE support, so any whacky, creative, outside-of-the-square ideas would be very welcome.


More From » dom

 Answers
31

http://www.quirksmode.org/js/events/DOMtree.html



jQuery now supports a way to attach events to existing and future elements corresponding to a selector: http://docs.jquery.com/Events/live#typefn



Another interesting find - http://james.padolsey.com/javascript/monitoring-dom-properties/


[#97320] Sunday, March 14, 2010, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
maureen

Total Points: 151
Total Questions: 110
Total Answers: 110

Location: Mali
Member since Fri, Dec 3, 2021
3 Years ago
maureen questions
Mon, Oct 11, 21, 00:00, 3 Years ago
Wed, Jun 30, 21, 00:00, 3 Years ago
Thu, Apr 15, 21, 00:00, 3 Years ago
Tue, Mar 16, 21, 00:00, 3 Years ago
Mon, Dec 7, 20, 00:00, 4 Years ago
;