22

I am reading this http://lists.w3.org/Archives/Public/public-webapps/2011JulSep/1622.html and it seems that Chrome's behavior contrasts to specification. If I understood the specs correctly, defining "subtree" for an element means that changes to the subtree of that element (including the element itself) should be reported. However, when executing this piece of code, I get nothing.

var observer = new WebKitMutationObserver(function(e){console.log(e);})
observer.observe(document.body, {subtree:true, attributes:true});
document.body.appendChild(document.createElement('div'));

What am I missing? Can somebody elaborate on this? Thanks!

zpavlinovic
  • 1,507
  • 1
  • 17
  • 36

3 Answers3

26

The documentation is unclear, but subtree is ignored unless you also specify childList:true.

The case for attributes and attributeFilter is the same.

Hope it still helps.

Guido
  • 46,642
  • 28
  • 120
  • 174
karnyj
  • 1,182
  • 1
  • 9
  • 10
12

According to this article:

childList: Set to true if additions and removals of the target node's child elements (including text nodes) are to be observed.

subtree: Set to true if mutations to not just target, but also target's descendants are to be observed.

This also explains subtree depending on childList.

Community
  • 1
  • 1
Lucat
  • 2,242
  • 1
  • 30
  • 41
  • 6
    what's the difference between `target's child elements` & `target's descendants`? – Ali Saeed Nov 26 '18 at 23:00
  • 12
    Child elements are the elements below the parent object (depth 1). Descendants are children of children and thus can be of any depth relative to the parent. – Lucat Nov 27 '18 at 11:32
5

In mutationObserver config, at least one of attributes, characterData, or childList needs to be set true.

Now, If you just set childList: true, then it will observe only the direct children (depth 1) of the target element and not the complete subtree.

To observe the complete subtree both childList and subtree needs to be set true.

e.g.

{
   childList: true,
   subtree: true
}

I hope, it's helpful.