Any way to use MutationObserver to watch for insertions of element with specified selector?

Viewed 437

Say I have an HTML hierarchy such as:

<div id="container">
  <div class="c">
    <div class="c"></div>
  </div>
  <div class="c"></div>
  <div class="c"></div>
</div>

I want to monitor the DOM for this HTML to know when a new element with class c is inserted anywhere. From what I can see of MutationObserver, there is no way to do this.

Instead I have to watch #container for childList events and have it watch the whole subtree. This would be fine if my real-world code only had the above, but the DOM is huge and getting dynamic insertions/deletions all the time that are not useful or needed.

Am I missing some way of using MutationObserver to watch for insertions of an element with a specific class?

1 Answers

One option is to use the Mutation Summary.

Their API is pretty simple:

var observer = new MutationSummary({
    callback: function (changes) {
        changes.forEach(function (change) {
            // Look only into added changes
            change.added.forEach(function (el) {
                 // el is the DOM element matched
                 console.log(el); 

                 // If you only need one match, you can disconnect the observer
                 // observer.disconnect();
            }) 
        })
    },
    queries: [{element:'.c'}],
    rootNode: document.getElementById('container')
});

It offers support for a simple subset of CSS selectors, but should be enough in your case.

Related