Consider the following code:
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
console.log(mutation.target.nodeName);
});
});
observer.observe(document, {
attributes: true,
childList: true,
characterData: true
});
<div>
<ol contenteditable oninput="">
<li>Press enter</li>
</ol>
</div>
which is a slight modification of this.
Interacting with the jsbin version page does not produce any log. Where am I wrong? Notice that if I substitute line
observer.observe(document, {
with
observer.observe(document.querySelector('ol'), {
the script turns on working...
It doesn't appear to work because you are not mutating anything that you are observing. You are neither changing
attributes: true
) of thedocument
node (which is understandable, sincedocument
doesn't have attributes)childList: true
): the only child node ofdocument
is the<html>
node, and you are not removing or replacing it.characterData: true
): you are not changing any Text, Comment, or ProcessingInstruction children ofdocument
(also understandable becausedocument
cannot have such children).If you replace the
<html>
node, you can see that the mutation observer works just as configured.What you are doing is changing the content of the
ol
element, which is a descendant ofdocument
.If you want to listen to these kind of changes, you have to set
subtree
to true:More information in the MDN documentation.