Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: How can I detect if the html has changed within a given element?

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!

like image 291
JohnIdol Avatar asked Feb 09 '11 20:02

JohnIdol


1 Answers

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.

like image 178
jAndy Avatar answered Nov 14 '22 23:11

jAndy