Search code examples
javascriptjqueryhtmldommutation-observers

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?


Solution

  • 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>