Last active
February 17, 2018 02:38
-
-
Save sheodox/a2c7f8c7021964842827 to your computer and use it in GitHub Desktop.
Mutation Observer - filtered node inserted callback
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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'; | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi,
I'm trying to do something like this.
But for some reason its not working.
Any suggestions ?