Skip to content

Instantly share code, notes, and snippets.

@nabrown
Last active September 12, 2018 13:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nabrown/fe68284ec3bb64ec7a569258565a25f0 to your computer and use it in GitHub Desktop.
Save nabrown/fe68284ec3bb64ec7a569258565a25f0 to your computer and use it in GitHub Desktop.
Using a mutation observer to watch for added child nodes
(function() {
// Select the node to observe
var targetNode = document.querySelector('#sqs-cart-root');
// If the targetNode exists on our page
if(targetNode){
// Watch when nodes are added to targetNode, or its descendants
var config = {
childList: true,
subtree: true
};
// When mutation is observed
var callback = function(mutationsList) {
var cartTitle = document.querySelector('.cart-title')
var continueShopping = '<br><a href="/all-courses" style="font-size: .5em;" id="continue-shopping">Continue Shopping</a>';
for(var mutation of mutationsList) {
// If we have a cart-title, but don't have our continue-shopping link yet, add it
if(cartTitle && !document.querySelector('#continue-shopping')){
cartTitle.innerHTML = cartTitle.innerHTML + continueShopping;
}else{
// Stop observing, we did what we needed
observer.disconnect();
}
}
};
// Create a new observer
var observer = new MutationObserver(callback);
// Start observing
observer.observe(targetNode, config);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment