Skip to content

Instantly share code, notes, and snippets.

@espretto
Last active February 7, 2023 12:29
Show Gist options
  • Save espretto/be509efc8b887d8e9e3cb6ad4aaaf8c4 to your computer and use it in GitHub Desktop.
Save espretto/be509efc8b887d8e9e3cb6ad4aaaf8c4 to your computer and use it in GitHub Desktop.
js: listen to dom changes
export function onNode(root, selector, handler) {
const target = root.querySelector(selector);
if (target) return handler(target);
new MutationObserver((records, observer) => {
const target = records
.filter(record => record.type === "childList")
.flatMap(record => record.addedNodes)
.find(node => node.nodeType === 1 && node.matches(selector));
if (target) {
observer.disconnect();
handler(target);
}
}).observe(root, {
attributes: false,
characterData: false,
childList: true,
subtree: true
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment