I want to monitor the complete HTML for the following changes:
- Whenever the "text" in a tag changes
- Whenever the "text" in a tag is added
- Whenever a new tag is added with a "text"
So, I just want to monitor for the text changes in the DOM. It could be because a new node was added with some text, it could be because a text in some existing tag changed from a
to b
, or it could be because the text was added in the otherwise empty tag <h1></h1> --> <h1>hello</h1>
How could I do this? I tried MutationObserver, but I find it very confusing and I am not able to use it correctly. I want to detect the newly added text and transform it via a transformation function. So for example,
<span>apple</span>
was added, it will be transformed as:
const transformedText = transform("apple");
// update the text
<span>transformedText</span>
Here is what I tried:
const config = {
attributes: false,
childList: true,
subtree: true,
characterData: true,
characterDataOldValue: true
};
const callback = function (mutationsList, observer) {
// Use traditional 'for loops' for IE 11
const dict = transformDictionary();
for (const mutation of mutationsList) {
if (mutation.type === "childList") {
for (const node of mutation.addedNodes) {
if (node.setAttribute) {
// TRANSFORM
}
}
if (mutation.target) {
// TRANSFORM
}
} else if (mutation.type === "characterDataOldValue") {
console.log(mutation);
} else if (mutation.type === "characterData") {
}
}
};
const o = new MutationObserver(callback).observe(document.body, config);
But it appears there are a lot many triggers for the node which is not a text node. For example a trigger will also be received for a node such as this complete div
:
<div>
wow
<div>
ok
<p>
<span>hello</span>
</p>
</div>
</div>
How can I achieve this?