Search code examples
javascriptdommutation-observers

Why MutationRecord[] is an array? (MutationObserve)


I am learning MutationObserve, and I can get it almost, but the only one I confuse with is why the parameter needs an array.

The document said:

An array of MutationRecord objects, describing each change that occurred;

I need a example which mutationRecordList.length > 1

<h2 id="testNode" onclick="addTimeNode(this)">Click me!</h2>

<script>
  function addTimeNode(node) {
    const nodeP = document.createElement("p")
    const today = new Date()
    nodeP.innerText = [today.getHours(), today.getMinutes(), today.getSeconds()].join(":")
    node.append(nodeP)
  }

  (
    () => {
      window.onload = () => {
        const observer = new MutationObserver((mutationRecordList, observer)=>{
          if (mutationRecordList.length > 1){
            console.log("Thanks. This is what I want!") // 👈
          }
          console.log(observer.name)
          for(const mutation of mutationRecordList) {
            const target = mutation.target
            switch(mutation.type) {
              case "childList":
                console.log('A child node has been added or removed.')
                break
            }
            if (target.childNodes.length > 2) {
              observer.disconnect()
              console.log('disconnect observer')
            }
          }
        })
        observer.name = "test observer"
        observer.observe(document.getElementById('testNode'), {
          // https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver/observe#parameters
          childList: true,
        })
      }
    }
  )()
</script>


Solution

  • Thank you @wOxxOm, and I think below is a demo for a lot of separate DOM operations in the same event loop cycle.

    <h2 id="testNode" onclick="addTimeNode(this)">Click me!</h2>
    
    <script>
      function addTimeNode(node) {
        const nodeP = document.createElement("p")
        const nodeP2 = document.createElement("p")
        nodeP.className = "test-add"
        nodeP2.className = "test-delete"
        const today = new Date()
        nodeP.innerText = [today.getHours(), today.getMinutes(), today.getSeconds()].join(":")
        node.append(nodeP, nodeP2)
        node.querySelector(`p[class="test-delete"]`).remove()
      }
    
      (
        () => {
          window.onload = () => {
            const observer = new MutationObserver((mutationRecordList, observer)=>{
              if (mutationRecordList.length > 1){
                console.log(`Thanks. This is what I want. length:${mutationRecordList.length}`) // 👈
              }
              console.log(observer.name)
              let i = 0
              for(const mutation of mutationRecordList) {
                console.log(`mutationRecordList[${i++}]`)
                const target = mutation.target
                switch(mutation.type) {
                  case "childList":
                    for (const node of mutation.addedNodes) {
                      console.log(`A child node has been added. className:${node.className}`)
                    }
    
                    for (const node of mutation.removedNodes) {
                      console.log(`A child node has been removed. className:${node.className}`)
                    }
                    break
                }
                if (target.childNodes.length > 2) {
                  observer.disconnect()
                  console.log('disconnect observer')
                }
              }
              console.log('----')
            })
            observer.name = "test observer"
            observer.observe(document.getElementById('testNode'), {
              // https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver/observe#parameters
              childList: true,
            })
          }
        }
      )()
    </script>