Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
333 views
in Technique[技术] by (71.8m points)

html - Can jQuery selectors be used with DOM mutation observers?

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 tree snippets. I don't know if they are exactly this or how they work really.

But when you are writing code to interact with a 3rd party site over which you have no control, say with a Greasemonkey script or Google Chrome user script, you have to inspect the tree of elements passed in to find which information is relevant to you.

This is much simpler with selectors, just like working with any DOM, than walking the tree manually, especially for cross-browser code.

Is there a way to use jQuery selectors with the data passed to HTML5 mutation observer callbacks?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

See this jsFiddle.

Suppose you had HTML like so:

<span class="myclass">
    <span class="myclass2">My <span class="boldly">vastly</span> improved</span>
    text.
</span>


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(<TextNode textContent="
 ">, span.myclass2, <TextNode textContent="
 text.
 ">)
true
jQuery(span.boldly)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...