I have been trying to log the updated cost information from an HTML document but have not been successful. I am sure it has to be that I am not using the mutation observer correctly. The js file is linked. Below is the HTML element that I am targeting.
HTML:
<span id="cost">0.00</span>
The JS file contains the following code:
const total = document.getElementById('cost');
console.log(total);
const options = {
characterData: true
};
function logCallback(mutations) {
console.log('called');
for (let mutation of mutations) {
if (mutation.type === 'characterData')
{
console.log('Mutation Detected: Price changed');
}
}
}
const observer = new MutationObserver(logCallback);
observer.observe(total.childNodes[0], options);
Your code would work if the code that was making the change changed the text node you're watching rather than destroying and replacing it, like this:
total.childNodes[0].nodeValue = "1.00";
Live Example:
const total = document.getElementById('cost');
const options = {
characterData: true,
};
function logCallback(mutations) {
console.log('called');
for (let mutation of mutations) {
if (mutation.type === 'characterData')
{
console.log('Mutation Detected: Price changed');
}
}
}
const observer = new MutationObserver(logCallback);
observer.observe(total.childNodes[0], options);
// Code that changes the element
total.childNodes[0].nodeValue = "1.00";
<span id="cost">0.00</span>
But the code making the change is probably destroying and replacing the child node, like this:
total.innerText = "1.00";
To handle that, you're probably best off watching for childList changes on the total element itself:
const total = document.getElementById('cost');
const options = {
childList: true,
};
function logCallback(mutations) {
console.log('called');
for (let mutation of mutations) {
console.log('Mutation Detected: Price changed');
}
}
const observer = new MutationObserver(logCallback);
observer.observe(total, options);
// Code that changes the element
total.innerText = "1.00";
<span id="cost">0.00</span>
You may need to refine that (I removed the if checking only for characterData changes), and/or combine it with what you already had (in case some other code changes the text differently), but that's the main issue with what you had.