Confused About MutationObserver

后端 未结 3 1666
遇见更好的自我
遇见更好的自我 2021-02-09 06:46

So I have been rattling my brain about using the MutationObserver and I haven\'t made any progress. I\'ve read about it on the W3C site and in the MDN. When reading it in the MD

3条回答
  •  时光说笑
    2021-02-09 07:10

    MutationObserver is a very powerful feature that lets you monitor all types of changes on a node/object in the DOM. In their example, they create the observer here:

    // create an observer instance
    var observer = new MutationObserver(function(mutations) {
      mutations.forEach(function(mutation) {
        console.log(mutation.type);
      });   
    });
    

    and call it here:

    // pass in the target node, as well as the observer options
    observer.observe(target, config);
    

    the target is a node, and the config tells it what to monitor on that node. There are various things you can monitor, and in their example they are monitoring when changes happen to the attributes, childList, and characterData. If any of those items change due to javascript manipulation or user action, observer will fire and give you information about what changed and let you take action based on the type of change. It's easiest to see it happen in the console.

    To test, make sure you have a valid target selected with:

    // select the target node
    var target = document.querySelector('#some-id');
    

提交回复
热议问题