You can use DOMNodeInserted
and DOMNodeRemoved
to check if elements are added or removed. Unfortunately, IE doesn't support this.
$('#myDiv').bind('DOMNodeInserted DOMNodeRemoved', function(event) {
if (event.type == 'DOMNodeInserted') {
alert('Content added! Current content:' + '
' + this.innerHTML);
} else {
alert('Content removed! Current content:' + '
' + this.innerHTML);
}
});
Update
You could save the initial contents and future changes with .data()
. Here's an example.
var div_eTypes = [],
div_changes = [];
$(function() {
$('#myDiv').each(function() {
this['data-initialContents'] = this.innerHTML;
}).bind('DOMNodeInserted DOMNodeRemoved', function(event) {
div_eTypes.concat(e.type.match(/insert|remove/));
div_changes.concat(this.innerHTML);
});
});
Example output:
> $('#myDiv').data('initialContents');
"<h1>Hello, world!</h1><p>This is an example.</p>"
> div_eTypes;
["insert", "insert", "remove"]
> div_changes;
["<iframe src='http://example.com'></iframe>", "<h4>IANA — Example domains</h4><iframe src='http://example.com'></iframe>", "<h4>IANA – Example domains</h4>"]
Update 2
You may want to include DOMSubtreeModified
as well, because I've found out that DOMNodeInserted
and DOMNodeRemoved
don't trigger if an element's innerHTML
is replaced directly. It still doesn't work in IE, but at least it works fine in other browsers.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…