Skip to content
Advertisement

Detect changes in the DOM

I want to execute a function when some div or input are added to the html. Is this possible?

For example, a text input is added, then the function should be called.

Advertisement

Answer

2015 update, new MutationObserver is supported by modern browsers:

Chrome 18+, Firefox 14+, IE 11+, Safari 6+

If you need to support older ones, you may try to fall back to other approaches like the ones mentioned in this 5 (!) year old answer below. There be dragons. Enjoy πŸ™‚


Someone else is changing the document? Because if you have full control over the changes you just need to create your own domChanged API – with a function or custom event – and trigger/call it everywhere you modify things.

The DOM Level-2 has Mutation event types, but older version of IE don’t support it. Note that the mutation events are deprecated in the DOM3 Events spec and have a performance penalty.

You can try to emulate mutation event with onpropertychange in IE (and fall back to the brute-force approach if non of them is available).

For a full domChange an interval could be an over-kill. Imagine that you need to store the current state of the whole document, and examine every element’s every property to be the same.

Maybe if you’re only interested in the elements and their order (as you mentioned in your question), a getElementsByTagName("*") can work. This will fire automatically if you add an element, remove an element, replace elements or change the structure of the document.

I wrote a proof of concept:

JavaScript

Usage:

JavaScript

This works on IE 5.5+, FF 2+, Chrome, Safari 3+ and Opera 9.6+

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement