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!

0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

11 Comments

Or what about DOMSubtreeModified event? (Only supported by Chrome, Firefox and Safari)
@Jan: If I understand OPs requirement correctly (detecting new nodes) this event will do just fine.
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: read the question again. I am basically trying to detect if given elements are being added to the div.
Oops, my bad. (Any alternative idea about how to achieve smt like this is also appreciated.)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.