I want to add content to the DOM if my MutationObserver detects a price change on any of my products.
I have a list of products, which is dynamic. Sometimes there could be 4 products, other times it could be a list of 20 products. If someone sorts or filters the list, the price of some of the products will update/change. I am observing this change via mutationobserver, specifically looking for characterdata.
For whatever items who's price updates, I want to add content to the DOM to let the customer know the price has changed/updated.
When I execute the code below, the content I attempt to append is appended as TEXT and not HTML. What am I doing wrong?
<div class="mainContainer">
<div class="item">
<div class="prodImg"></div>
<div class="optionOne">{{price}}</div>
<div class="optionTwo">{{price}}</div>
</div>
<div class="item">
<div class="prodImg"></div>
<div class="optionOne">{{price}}</div>
<div class="optionTwo">{{price}}</div>
</div>
<div class="item">
<div class="prodImg"></div>
<div class="optionOne">{{price}}</div>
<div class="optionTwo">{{price}}</div>
</div>
<div class="item">
<div class="prodImg"></div>
<div class="optionOne">{{price}}</div>
<div class="optionTwo">{{price}}</div>
</div>
</div>
var targetNode = document.querySelector(".mainContainer");
var config = { attributes: true, childList: true, subtree: true, characterData:true };
var callback = (mutationList, observer) => {
for (const mutation of mutationList) {
if (mutation.type === 'characterData') {
console.log('char data found');
if (mutation.target.parentElement.className === 'optionOne') {
$this = mutation.target.parentNode.closest('.item')
$this.prepend('<div class="optChanged">Price changed!</div>')
}
}
}
};
var observer = new MutationObserver(callback);
observer.observe(targetNode, config);