UNPKG

dom-watchdog

Version:

Observe mudanças no DOM com callbacks simples.

36 lines (35 loc) 1.33 kB
export function watch(selector, options, observerOptions) { const target = document.querySelector(selector); if (!target) throw new Error(`Element ${selector} not found`); const observer = new MutationObserver((mutations) => { for (const mutation of mutations) { if (mutation.type === 'childList') { mutation.addedNodes.forEach((node) => { if (node.nodeType === 1 && options.onAdd) options.onAdd(node); }); mutation.removedNodes.forEach((node) => { if (node.nodeType === 1 && options.onRemove) options.onRemove(node); }); } if (mutation.type === 'attributes' && options.onChange) { options.onChange(mutation.target); } if (mutation.type === 'characterData' && options.onChange) { const parentElement = mutation.target.parentElement; if (parentElement) { options.onChange(parentElement); } } } }); observer.observe(target, { childList: true, attributes: true, subtree: true, ...observerOptions, }); return () => observer.disconnect(); }