iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
💨

Detecting Changes in Child Elements with MutationObserver

に公開
2023/07/22

Conclusion

  • subtree: true
  • Cannot detect changes even when using childList

Code Example

<!-- HTML code -->
<div id="list-item">
    <li  class="test">1</li>
    <li class="test">2</li>
    <li class="test">3</li>
</div>
    // Get the observation target
    const target = document.getElementById('list-item')

    // Create an observer
    const observer = new MutationObserver(records => {
        // Define the processing when a change occurs
        console.log("Detected")
    })

    // Start observing
    observer.observe(target, {
        attributes: true,
        subtree: true,
    })

Differences Between subtree and childList

  • subtree
    • Monitoring changes to the target node and its descendants
      • Reacts to class changes, text changes, etc.
  • childList
    • Monitoring changes (additions/removals) to the target node's child nodes (including text nodes and comment nodes)
      • Reacts to the addition and deletion of elements

Descriptions of childList varied depending on the site, but it seems childList only reacts to deletions and additions... (Confirmed by myself). The following sites were helpful 🙏

Note

characterData: true, // Monitor changes to text nodes

Note that when text in a p tag or similar is changed, it won't be detected unless characterData is set to true.

References

https://www.mitsue.co.jp/knowledge/blog/frontend/201803/28_1056.html
https://www.webdesignleaves.com/pr/jquery/mutationObserver.html

Discussion