Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MutationObserver characterData usage without childList

Up until recently I thought that childList : true on MutationObserver was to be used when child node is being added/removed e.g from <span id='mama-span'> </span> to <span id='mama-span'><span id='baby-span'></span></span>

and characterData : true was to be used when text inside observed element chages e.t <span> </span> to <span> with some text </span>. It turns out that for text change to be observed one needs to add childList : true.

Can anyone think of situation in which characterData would be used without childList? What is it used for?

like image 652
Matas Vaitkevicius Avatar asked Nov 04 '15 12:11

Matas Vaitkevicius


People also ask

When would you use a mutation observer?

MutationObserver can react to changes in DOM – attributes, text content and adding/removing elements. We can use it to track changes introduced by other parts of our code, as well as to integrate with third-party scripts.

How do you implement MutationObserver?

This is done by setting the characterData property to true in the options object. Here's the code: let options = { characterData: true }, observer = new MutationObserver(mCallback); function mCallback(mutations) { for (let mutation of mutations) { if (mutation. type === 'characterData') { // Do something here... } } }

How do you stop MutationObserver?

disconnect() The MutationObserver method disconnect() tells the observer to stop watching for mutations. The observer can be reused by calling its observe() method again.

Which of the following methods are available to stop observing DOM changes?

The observer object will call the resolve() function once the element is available and stop observing the DOM tree.


1 Answers

You can observe a text node directly. In that case you don't need to observe childList. There are many cases where it could be useful, in a contenteditable element for example. Like this:

// select the target node
var target = document.querySelector('#some-id').childNodes[0];

// create an observer instance
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.log(mutation.type);
  });    
});
 
// configuration of the observer:
var config = { attributes: true, childList: false, characterData: true };
 
// pass in the target node, as well as the observer options
observer.observe(target, config);
<div id='some-id' contenteditable='true'>Modify content</div>
like image 95
Julien Grégoire Avatar answered Oct 06 '22 00:10

Julien Grégoire