Is there a way to retrieve all removed nodes from the DOM that have specific classes using CSS selectors? Below is an example of how it can be done with some complexity, but is there a simpler and more general approach?
new MutationObserver(mut => {
removed_nodes = removed_nodes(mut);
console.log(removed_nodes.querySelectorAll('.hello'));
console.log(removed_nodes.querySelectorAll('.myclass #a'));
}).observe(document.querySelector("html"), { childList: true, subtree: true });
Below is a sample code snippet specifically for filtering removed nodes by classes:
selected_classes = {"banana": 0, "hello": 0};
new MutationObserver(mut => {
for (m of mut) {
for (n of m.removedNodes) {
if (n.classList) // text node don't have a classList!
for (c of n.classList.values())
if (c in selected_classes)
console.log("selected_classes found:", n);
if (n.childNodes)
for (n2 of n.childNodes.values())
if (n2.classList)
for (c of n2.classList.values())
if (c in selected_classes)
console.log("selected_classes found:", n2);
}
}
}).observe(document.querySelector("html"), { childList: true, subtree: true });
document.getElementById("c").onclick = () => { document.getElementById("b").remove(); }
<div id="a">a</div>
<div id="b" class="tomato">b
<div id="b1">b1</div>
<div id="b2" class="hello">b2 (class hello)</div>
</div>
<div id="c">Click to remove b</div>