Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
130
rated 0 times [  133] [ 3]  / answers: 1 / hits: 20023  / 8 Years ago, sat, october 22, 2016, 12:00:00

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.


More From » jquery

 Answers
5

It's because textContent triggers a different change than innerHTML, and your observer configuration is not configured to observe the changes made by textContent.


textContent changes the child text node of the target. According to MDN setting textContent:



Setting this property on a node removes all of its children and
replaces them with a single text node with the given value.



While innerHTML changes the the element itself, and its subtree.


So to catch innerHTML your configuration should be:


var config = { characterData: true, attributes: false, childList: false, subtree: true };

While to catch textContent use:


var config = { characterData: false, attributes: false, childList: true, subtree: false };

Demo:




function mutate(mutations) {
mutations.forEach(function(mutation) {
alert(mutation.type);
});
}

setTimeout(function() {
document.querySelector('div#mainContainer > p').textContent = 'some other text.';
}, 1000);

var target = document.querySelector('div#mainContainer > p')
var observer = new MutationObserver( mutate );
var config = { characterData: false, attributes: false, childList: true, subtree: false };

observer.observe(target, config);

<div id=mainContainer>
<h1>Heading</h1>
<p>Paragraph.</p>
</div>




[#60313] Wednesday, October 19, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
keyanah

Total Points: 642
Total Questions: 93
Total Answers: 114

Location: Virgin Islands (U.S.)
Member since Tue, Jul 7, 2020
4 Years ago
;