Last active
May 3, 2026 22:27
-
-
Save rndme/1d2b3945efae4605dc2cc5ee33160fc1 to your computer and use it in GitHub Desktop.
live querySelector tool w/callback and observation
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
| // A live querySelector tool with a callback that runs now and auto-applies to newly added elements. | |
| function foreverEach(selector, fnCallback, root = document.documentElement){ | |
| var used = new WeakSet(); | |
| function isNew(elm){ if(!used.has(elm)) return used.add(elm); } | |
| [...root.querySelectorAll(selector)].filter(isNew).forEach(fnCallback); | |
| return { | |
| ob: new MutationObserver(function _addWatcher(mutationsList) { | |
| for (var x of mutationsList) | |
| if (x.type === 'childList') [...x.addedNodes] | |
| .filter(x=>x.matches && x.matches(selector)) | |
| .filter(isNew) | |
| .forEach( fnCallback ); | |
| }).observe(root, { | |
| childList: true, subtree: true | |
| }), | |
| elms: used, | |
| selector, | |
| fnCallback, | |
| root, | |
| $: x=>[...root.querySelectorAll(selector)] | |
| }; | |
| } // end foreverEach() | |
| /* // uninspired example: current and newly-added <P> tags will get a random number title attribute | |
| var Ps = foreverEach("p", x=>{ | |
| x.title = Math.random(); | |
| }); | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment