Can mutations observer be used to observe the addition and removal of a single node?

冷暖自知 提交于 2021-01-07 02:51:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!