Can a single MutationObserver object observe multiple targets?

后端 未结 1 1638
别跟我提以往
别跟我提以往 2021-02-01 15:37

I would like to use a MutationObserver object to observe changes to some of my DOM nodes.

The docs give an example of creating a MutationObserver object an

1条回答
  •  抹茶落季
    2021-02-01 16:04

    The observer will now be watching two targets - target and target2 per your definitions. No error will be thrown, and target will not be "unregistered" in favor of target2. No unexpected or other behaviors will be exhibited.

    Here is a sample which uses the same MutationObserver on two contenteditable elements. To view this, delete the node from each contenteditable element and view the behavior span across both observed elements.

    Span A
    Span B

    var observer = new MutationObserver(function(mutations) {
      mutations.forEach(function(mutation) {
          //console.log($(mutation.removedNodes)); // <<-- includes text nodes
    
          $(mutation.removedNodes).each(function(value, index) {
              if(this.nodeType === 1) {
                  console.log(this)
              }
          });
      });
    });
    
    var config = { attributes: true, childList: true, characterData: true };
    
    observer.observe($('#myTextArea')[0], config);
    
    observer.observe($('#myTextArea2')[0], config);
    

    JSFiddle Link - demo

    Note that I have recycled the same config for this first demo, but, placing a new config will be exclusive to that observed element. Taking your example as defined in config2, if used on #myTextArea2, you'll not see the logged node per the configuration options, but notice that the observer for #myTextArea is unaffected.

    JSFiddle Link - demo - configuration exclusiveness

    0 讨论(0)
提交回复
热议问题