I've found the MutationObserver documentation to be rather confusing. I would like to observe the document body for when DIV elements having the class superelement
are added to the DOM.
<div class="superelement" style="display:none;2"></div>
I've managed to glue this snippet together:
const observer = new MutationObserver(onMutation);
observer.observe(document, {
childList: true,
subtree: true,
});
function onMutation(mutations) {
const found = [];
for (const { addedNodes } of mutations) {
for (const node of addedNodes) {
if (!node.tagName) {
continue; // not an element
} else {
if (node.classList.contains('superelement')) {
console.log(node)
}
}
}
}
}
Is there no cleaner way to iterate all elements that were added? I can imagine this being rather slow.