'How to watch the content of a div?
I need to watch the content of a div on my "shop" page that is the number of items added to a cart. The content of this div is being populated from third-party javascript and only on one page of my site.
I need to take this value when it's updated by the third-party script, and place it in another part of my html, in a separate component, that exists on every page. (currently the cart only shows on the shop page, but I want it to show in the header).
What is the best approach to do this?
I believe I will need to make an ajax call to the 'shop' page and check the innerHTML of the cart item count div, then populate that value. This allows me to pull it initially, but then I would still need to watch that value as people add items to the cart (only from the shop page).
Thank you for pointing me in the right direction.
Solution 1:[1]
I need to watch the content of a div on my "shop" page that is the number of items added to a cart. The content of this div is being populated from third-party javascript and only on one page of my site.
This is a general JavaScript question - React will help you populate divs from data, but won't help you watch divs created by third party JS. I've removed the 'react' tag from your question.
To watch a div, use MutationObserver. From MDN:
// Select the node that will be observed for mutations
const targetNode = document.getElementById('some-id');
// Options for the observer (which mutations to observe)
const config = { attributes: true, childList: true, subtree: true };
// Callback function to execute when mutations are observed
const callback = function(mutationsList, observer) {
// Use traditional 'for loops' for IE 11
for(const mutation of mutationsList) {
if (mutation.type === 'childList') {
console.log('A child node has been added or removed.');
}
else if (mutation.type === 'attributes') {
console.log('The ' + mutation.attributeName + ' attribute was modified.');
}
}
};
// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(targetNode, config);
// Later, you can stop observing
observer.disconnect();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mikemaccana |
