Can jQuery selectors be used with DOM mutation observers?

后端 未结 4 1250
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-04 10:23

HTML5 includes a concept of \"mutation observers\" to monitor changes to the browser\'s DOM.

Your observer callback will be passed data which looks a lot like DOM tr

4条回答
  •  天命终不由人
    2020-12-04 11:00

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

    See this jsFiddle.

    Suppose you had HTML like so:

    
        My vastly improved
        text.
    
    


    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") );
            }
        } );
    }
    

    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(, span.myclass2, )
    true
    jQuery(span.boldly)
    

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

提交回复
热议问题