我必须在元素上注册哪种事件类型以跟踪添加子元素

Which event type I have to register on element to track adding subelements

我正在寻找我的 div.

中添加了如何通知元素的方式

样式元素由第三方组件添加,我只知道将添加到哪个元素中。 我可以在 div 上使用带有 DOM 断点的 DevTools 进行跟踪,但这可能是 Chrome.

的内部功能

有没有办法监听与直接子树修改相关的触发事件?像这样:

document.getElementById("my-div").addEventListener("subtree-modification", function(event) { ... my event handler });

我在文档中找到了有关 MutationObserver 的信息。这是前进的方向吗?你能给我举个例子吗?

如您所述,可以使用 MutationObserver:

// Select the node that will be observed for mutations:
const targetNode = document.getElementById('target');

// Options for the observer (which mutations to observe)
const config = { attributes: true, childList: true, subtree: true };

// Create an observer instance linked to the callback function
const observer = new MutationObserver((mutationsList, observer) => {
  mutationsList.forEach((mutation) => {
    if (mutation.type === 'childList') {
      console.log('A child node has been added or removed.');
    } else if (mutation.type === 'attributes') {
      console.log('The ' + mutation.attributeName + ' attribute was modified.');
    }
  });
});

// Start observing the target node for configured mutations
observer.observe(targetNode, config);

// Modify the observer element to see this in action:
targetNode.innerText = 'Updated content.';
targetNode.setAttribute('data-foo', 'bar');
targetNode.removeAttribute('data-foo');
<div id="target">Initial content.</div>

MutationObserver 将起作用。 (相比之下,通过 addEventListener 的突变事件已被弃用且速度缓慢,最好避免它们。)例如:

console.log('script start');
const myDiv = document.getElementById("my-div");

new MutationObserver((mutations, observer) => {
  console.log('Change observed');
  // Once the change is seen, don't need the observer anymore
  observer.disconnect();
})
  .observe(myDiv, { childList: true });


setTimeout(() => {
  myDiv.appendChild(document.createElement('span')).textContent = 'span content';
}, 3000);
<div id="my-div">my div </div>

childList: true 将监视观察元素的任何 直接子元素 的变化。如果您想观察 任何后代 的变化,请同时使用 subtree: true

{ childList: true, subtree: true }

但深度观察者的成本很高 - 请记住在它们完成您的需求后将其移除。

这里是一个用法的例子,它很简单 MutationObserver 监视 remove/add 元素,注意我使用 setTimeout 在 1 秒后删除 <li> 元素,另一个2 秒后添加元素:

function callback(mutationList, observer) {
  mutationList.forEach((mutation) => {
    switch (mutation.type) {
      case "childList":
        if (mutation.removedNodes.length) {
          console.log("removed element here");
        }

        if (mutation.addedNodes.length) {
          console.log("Added element here");
        }
        break;
    }
  });
}

var targetNode = document.querySelector("#someElement");
var observerOptions = {
  childList: true,
  attributes: true,
  subtree: true, //Omit or set to false to observe only changes to the parent node.
};

var observer = new MutationObserver(callback);
observer.observe(targetNode, observerOptions);

setTimeout(function () {
  document.getElementById("el2").remove();
}, 1500);

setTimeout(function () {
  let newLi = document.createElement("li");
  newLi.innerHTML = "new Li";
  document.getElementById("ulElm").appendChild(newLi);
}, 2000);
<div id="someElement">
  <ul id="ulElm">
    <li> element 1 </li>
    <li id="el2"> element 2 </li>
    <li> element 3 </li>
    <li> element 4 </li>
  </ul>
</div>