Monitoring DOM Changes with MutationObserver
How to detect when a specific element or text is added to the DOM?
I have a OneTrust cookie banner, and I want to execute JavaScript when the banner is shown to the user. I can use the OneTrust method function OptanonWrapper() {} for this, but I want a similar approach for detecting the Unbounce sticky bar. Many others need this for different scenarios, so is there any method available to detect when a new element is added to the DOM, and if it is, I want to execute my code?
If you're dynamically loading content or need to know when certain elements appear in the DOM, MutationObserver is a powerful tool in your JavaScript toolbox.
In this blog, I will show you how to detect when the OneTrust cookie banner is added. You can follow a similar approach and modify the code to suit your needs
Monitoring DOM Changes to Detect the OneTrust Cookie Banner with MutationObserver
You can use the following approach. MutationObserver is a built-in JavaScript API that observes changes in the DOM and triggers a callback when changes occur, such as when new elements are added (like the OneTrust cookie banner).
This code will continuously monitor for the appearance of the OneTrust banner and can be adapted to take any specific action once the banner is detected.
const domObserver = new MutationObserver((mutations) => { mutations.forEach((mutation) => { mutation.addedNodes.forEach((node) => { if (node.id === 'onetrust-banner-sdk') { alert('OneTrust cookie banner is shown!'); /* Write Your Code */ domObserver.disconnect(); } }); }); }); domObserver.observe(document.body, { childList: true, subtree: true });
The observer immediately checks if the #onetrust-banner-sdk node is present after any DOM mutation, and once it finds the target node, it disconnects the observer. It does not rely on iterating over all added nodes but instead directly queries the DOM.