Last active
September 12, 2018 13:34
-
-
Save nabrown/fe68284ec3bb64ec7a569258565a25f0 to your computer and use it in GitHub Desktop.
Using a mutation observer to watch for added child nodes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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