How to detect text change with Mutation Observer and JavaScript?

Sometimes, we want to detect text change with Mutation Observer and JavaScript?.

In this article, we’ll look at how to detect text change with Mutation Observer and JavaScript.

How to detect text change with Mutation Observer and JavaScript?

To detect text change with Mutation Observer and JavaScript, we can set the characterData option to true.

For instance, we write:

<div>

</div>

to add a div.

Then we write:

const mutate = (mutations) => {
  mutations.forEach((mutation) => {
    console.log(mutation);
  });
}

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

observer.observe(target, config);

setTimeout(() => {
  target.textContent = 'hello world';
}, 1000);

We create a MutationObserver instance with the mutate function as the callback.

And we call observe with a config that has characterData set to true to observe text node changes.

Therefore, when we change the textContent of target to 'hello world', mutate would run.

Conclusion

To detect text change with Mutation Observer and JavaScript, we can set the characterData option to true.