Skip to content

Instantly share code, notes, and snippets.

@sheodox
Last active February 17, 2018 02:38
Show Gist options
  • Select an option

  • Save sheodox/a2c7f8c7021964842827 to your computer and use it in GitHub Desktop.

Select an option

Save sheodox/a2c7f8c7021964842827 to your computer and use it in GitHub Desktop.
Mutation Observer - filtered node inserted callback
function filteredNewNodeCallback(root, selector, callback) {
var obs, i;
if (!root || !selector || !callback) {
return;
}
function filterAndCallback(node) {
var matches = [], childMatches;
if (node.matches(selector)){
matches.push(node);
}
childMatches = node.querySelectorAll(selector);
if (childMatches.length !== 0) {
matches = matches.concat([].slice.call(childMatches))
}
matches.map(callback);
}
obs = new MutationObserver(function(mutations){
mutations.forEach(function(mutation){
for(i = 0; i < mutation.addedNodes.length; i++) {
if (mutation.addedNodes[i].nodeType === 1) {
filterAndCallback(mutation.addedNodes[i]);
}
}
})
});
obs.observe(root, {childList: true, subtree: true});
}
/* test stuff */
//make new tweets on twitter red
filteredNewNodeCallback(document.querySelector('#timeline'), '.js-stream-item', function(tweet){
tweet.style.background = 'red';
});
@AshikNesin
Copy link

Hi,

I'm trying to do something like this.

But for some reason its not working.

Any suggestions ?

   var $target = $('#timeline')
   new MutationObserver(() => console.log('hell yeahhhh'))
          .observe($target.get(0), {childList: true,subtree: true});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment