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?
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:
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:which shows that you can use normal jQuery selection methods on the returned node sets.
I know this is an old question but perhaps this can help others searching for alternative solutions. I recently learned about Mutation Observers and wanted to experiment with using them alongside jQuery. I came up with two possible approaches and turned them into plugins. The code is available here.
The first approach (
jquery.observeWithEvents.js
) uses jQuery'strigger()
function to trigger either aninsertNode
orremoveNode
event which can be bound to via jQuery'son()
function. The second approach (jquery.observeWithCallbacks.js
) uses traditional callback parameters. Please take a look at the README for examples and usage.I don't have any personal code snippets for this one, but I have three resources that may help:
Example from link #3 'jquery-mutation-summary' library:
I was working on a very similar problem for a Stack Exchange script I'm working on, and I needed to be able to monitor the DOM for changes. The jQuery docs didn't have anything helpful, but I did discover that the DOMNodeInserted event works in Chrome:
I'm not 100% sure if this works in Firefox as I haven't got that far yet in the development process. Hope this helps!