10

In javascript, possibly using jQuery, how can I detect if the html content of a given element has changed?

I'd like to be able to do somthing like:

$('#myDiv').change(function(){
  // do some stuff
});

I am basically trying to detect if given elements are being added to the div or if the inner html of given elements (such as labels) has changed and then hide or show the div depending on the content.

Any alternative idea about how to achieve smt like this is also appreciated.

I am hoping I won't have to revert to some obscure plugin to do this!

NOTE: this needs to work at least in IE8!

JohnIdol
  • 48,899
  • 61
  • 158
  • 242

1 Answers1

22

You can use the DOM Level 3 event DOMNodeInserted. Example:

$('#myDiv').bind('DOMNodeInserted', function(e) {
    console.log('element: ', e.target, ' was inserted');
});

Demo: http://www.jsfiddle.net/vsgdZ/1/

The event will fire whenever a new node was appended to the element on which you bind the handler.

Lewis
  • 3,375
  • 3
  • 29
  • 26
jAndy
  • 231,737
  • 57
  • 305
  • 359
  • Or what about `DOMSubtreeModified` event? (Only supported by Chrome, Firefox and Safari) – Jan Feb 09 '11 at 20:52
  • @Jan: If I understand OPs requirement correctly (detecting new nodes) this event will do just fine. – jAndy Feb 09 '11 at 20:53
  • and would this event fire if the className of one of the children is changed? That is also 'changing of content'. I'm not saying your solution is wrong, just suggesting another event that might help if he needs more than detecting insertion of new children. – Jan Feb 09 '11 at 21:43
  • @Jan: read the question again. `I am basically trying to detect if given elements are being added to the div`. – jAndy Feb 09 '11 at 21:50
  • 1
    Oops, my bad. (`Any alternative idea about how to achieve smt like this is also appreciated.`) – Jan Feb 09 '11 at 22:01
  • great answer, and you got my +1. I'll bring it one step further: how about listening for any html changes? is there an event that would cater for that (for example some inner html injected in an element or the likes)? – JohnIdol Feb 09 '11 at 22:15
  • @JohnIdol: for that purpose, see Jan's suggestion. `DOMSubtreeModified`. Anyway, `DOMNodeInserted` will also fire, you create a new node by changing the `innerHTML` property. So it really depends what kind of change you're looking for. – jAndy Feb 09 '11 at 22:29
  • @jAndy I need to track both node inserted type of things but also innerHtml on present nodes (i.e. a paragraph or a label added, or some text injected in a label or a paragraph). Also needs to work in IE! :) – JohnIdol Feb 09 '11 at 22:31
  • @JohnIdol: If you just want to watch for new nodes, you can rely on `DOMNodeInserted` (AFAIK). See updated **Demo**. – jAndy Feb 09 '11 at 22:33
  • `' was inserted` needs a closing `'` – pnairn Sep 04 '13 at 04:11
  • Warning: This is `Deprecated` ! see https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Mutation_events – Adriano Jul 30 '14 at 11:56