This is an old post but I thought I would add my thoughts, I too have had a similar issue with trying to detect changes to an element that is inside the body
element.
I am not saying that my solution is good by any means but seeing as this question has no accepted answer perhaps my thoughts can help to find a solution.
My issue is that I want to create a JavaScript solution to detecting insertions inside of the <div id="root"></div>
element used by ReactJS applications, the reasons as to why I want to do this are not important.
I found that attaching my MutationObserver
to document
, document.documentElement
or document.body
didn't provide any solutions. I ended up having to place my MutationObserver
inside of a loop and attach it to each child element within body
so I could detect the changes.
Here is my code, I am sure there is a better way to do this but I have not found it yet:
// Public function
export function listenForDynamicComponents() {
// Create the observer
const observer = new MutationObserver((mutations) => {
// Loop each mutation
for (let i = 0; i < mutations.length; i++) {
const mutation = mutations[i];
// Check the mutation has added nodes
if (mutation.addedNodes.length > 0) {
const newNodes = mutation.addedNodes;
// Loop though each of the added nodes
for (let j = 0; j < newNodes.length; j++) {
const node = newNodes[j];
// Check if current node is a component
if (node.nodeType === 1 && node.hasAttribute('data-module')) {
// Do something here
}
// Loop though the children of each of the added nodes
for (let k = 0; k < node.childNodes.length; k++) {
const childNode = node.childNodes[k];
// Check if current child node is a compoennt
if (childNode.nodeType === 1 && childNode.hasAttribute('data-module')) {
// Do something here
}
}
}
}
}
});
// Get all nodes within body
const bodyNodes = document.body.childNodes;
// Loop though all child nodes of body
for (let i = 0; i < bodyNodes.length; i++) {
const node = bodyNodes[i];
// Observe on each child node of body
observer.observe(node, {
attributes: false,
characterData: false,
childList: true,
subtree: true,
attributeOldValue: false,
characterDataOldValue: false
});
}
}
I hope this helps.