问题
I want to observe a single node for being added to the page. I do not want to get any notifications about any other mutations. I have no way of knowing where on the page the node will be appended.
Is this possible? As far as I can tell, it's only possible to observe the child list of a parent element: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserverInit
回答1:
No, it is not possible. Mutation observers only observe added child nodes of a target, not the adding or removing of a target node.
const div = document.createElement("div");
div.textContent = "I've been added";
const selfObserver = new MutationObserver((mutList) => {
mutList.forEach((mut) => console.log("self", mut));
})
selfObserver.observe(div, {childList: true});
setTimeout(() => { document.body.append(div); }, 150);
If you want to observe just a single node being added or removed, it's not possible. You must observe every single node being added to the page, then iterate over their entire subtree searching for the specific node you'd like to find. It's extremely inefficient, and it's the best there is.
来源:https://stackoverflow.com/questions/65587654/can-mutations-observer-be-used-to-observe-the-addition-and-removal-of-a-single-n