I'm scratching my head as to why MutationObserver doesn't detect text changes done using textContent.
HTML
<div id="mainContainer">
<h1>Heading</h1>
<p>Paragraph.</p>
</div>
JavaScript
function mutate(mutations) {
mutations.forEach(function(mutation) {
alert(mutation.type);
});
}
jQuery(document).ready(function() {
setTimeout(function() {
document.querySelector('div#mainContainer > p').textContent = 'Some other text.';
}, 2000);
var target = document.querySelector('div#mainContainer > p')
var observer = new MutationObserver( mutate );
var config = { characterData: true, attributes: false, childList: false, subtree: true };
observer.observe(target, config);
});
In the above script, the paragraph element's text content clearly changes but MutationObserver doesn't detect it.
However, if you change textContent to innerHTML, you will be alerted that the "characterData" has changed.
Why does MutationObserver detect innerHTML but not textContent?
Here is the JS Fiddle:
https://jsfiddle.net/0vp8t8x7/
Notice that you'll only get alerted if you change textContent to innerHTML.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…