59

Why is the DOMSubtreeModified event deprecated and what are we supposed to use instead?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
huyz
  • 2,297
  • 3
  • 25
  • 34

2 Answers2

53

If you scroll down a bit, you see:

Warning! The MutationEvent interface was introduced in DOM Level 2 Events, but has not yet been completely and interoperably implemented across user agents. In addition, there have been critiques that the interface, as designed, introduces a performance and implementation challenge. A new specification is under development with the aim of addressing the use cases that mutation events solves, but in more performant manner. Thus, this specification describes mutation events for reference and completeness of legacy behavior, but deprecates the use of both the MutationEvent interface and the MutationNameEvent interface.

The replacement API is mutation observers, which are fully specified in the DOM Living Standard that supercedes all of the DOM level X silliness.

Domenic
  • 110,262
  • 41
  • 219
  • 271
  • 4
    @ TJ - no down. The one above is *DOMNodeRemovedFromDocument*. :-) – RobG Jul 12 '11 at 05:36
  • 3
    Replacement will come in DOM Level 4 http://dvcs.w3.org/hg/domcore/raw-file/tip/Overview.html#mutation-observers and it seems there is some progress in Chromium https://bugs.webkit.org/show_bug.cgi?id=73851 – Hrant Khachatrian Dec 15 '11 at 19:25
  • 1
    A great hack to replace the `MutationEvent` interface is [`animationStart` and some CSS](http://stackoverflow.com/a/13835369/237285). – Andres Riofrio Dec 12 '12 at 08:15
  • The problem of the animationStart being, it only works for insertion of nodes. Not for node removal, attribute edition or text changes. It's also single-node, where `DOMSubtreeModified` allows watching a whole tree from a root node. – xmo Aug 22 '13 at 11:01
26

I think the replacement will be mutation observers: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

var whatToObserve = {childList: true, attributes: true, subtree: true, attributeOldValue: true, attributeFilter: ['class', 'style']};
var mutationObserver = new MutationObserver(function(mutationRecords) {
  $.each(mutationRecords, function(index, mutationRecord) {
    if (mutationRecord.type === 'childList') {
      if (mutationRecord.addedNodes.length > 0) {
        //DOM node added, do something
      }
      else if (mutationRecord.removedNodes.length > 0) {
        //DOM node removed, do something
      }
    }
    else if (mutationRecord.type === 'attributes') {
      if (mutationRecord.attributeName === 'class') {
        //class changed, do something
      }
    }
  });
});
mutationObserver.observe(document.body, whatToObserve);
ralfthewise
  • 543
  • 7
  • 10
  • I fail to understand the improvement that this makes. The code needed for achieving the same result seems to be bigger and less intuitive, and I don't get the internal benefits of how it works. – S. Dre May 12 '22 at 10:07