Can jQuery selectors be used with DOM mutation observers?

Yes, you can use jQuery selectors on data returned to mutation observer callbacks.

See this jsFiddle.

Suppose you had HTML like so and you set an observer, like so:

var targetNodes = $(".myclass");
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
var myObserver = new MutationObserver(mutationHandler);
var obsConfig = {
  childList: true,
  characterData: true,
  attributes: true,
  subtree: true
};

//--- Add a target node to the observer. Can only add one node at a time.
targetNodes.each(function() {
  myObserver.observe(this, obsConfig);
});

function mutationHandler(mutationRecords) {
  console.info("mutationHandler:");

  mutationRecords.forEach(function(mutation) {
    console.log(mutation.type);

    if (typeof mutation.removedNodes == "object") {
      var jq = $(mutation.removedNodes);
      console.log(jq);
      console.log(jq.is("span.myclass2"));
      console.log(jq.find("span"));
    }
  });
}
setTimeout(function() {  
  $(".myclass").html ("[censored!]");
},1000)  
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<span class="myclass"> 
  <span class="myclass2">My 
    <span class="boldly">vastly</span> improved
  </span> 
  text.
</span>

You’ll note that we can jQuery on the mutation.removedNodes.


If you then run $(".myclass").html ("[censored!]"); from the console you will get this from Chrome and Firefox:

mutationHandler:
childList
jQuery(<TextNode textContent="\n ">, span.myclass2, <TextNode textContent="\n text.\n ">)
true
jQuery(span.boldly)

which shows that you can use normal jQuery selection methods on the returned node sets.

Leave a Comment

tech