JavaScript中如何监听dom的节点变化

DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="./js/loadsource.js">script>
    <title>MutationObserver 监听domtitle>
  head>
  <body>
    <div class="parent">
      <header>
        <h1>事件循环h1>
      header>
      <main id="main">
        <button type="button" class="btn btn-primary">点击button>
      main>
    div>

    <script>
      const button = document.querySelector('[type=button]');
      button.addEventListener('click', (e) => {
        if (e.target.tagName === 'BUTTON') {
          let parent = e.target.parentNode;
          let childList = [...parent.children];

          if (childList[1] && childList[1]?.tagName === 'DIV') {
            parent.removeChild(childList[1]);
          } else {
            let div = document.createElement('div');
            div.className = 'div-show';
            div.innerText = 'hello world';
            parent.appendChild(div);
          }
        }
      });

      const targetNode = document.querySelector('#main');
      const observerOptions = {
        childList: true,
        attributes: false,
        subtree: true, // 子树中的所有节点
      };

      const observer = new MutationObserver((mutationsList, observer) => {
        for (let mutation of mutationsList) {
          if (mutation.type === 'childList') {
            console.log('A child node has been added or removed.');
          }
        }
      });

      observer.observe(targetNode, observerOptions);
    script>
  body>
html>


你可能感兴趣的:(javascript,前端,vue.js)