Observe changes in a DOM element with simple callbacks.
npm install dom-watchdogimport { watch } from "dom-watchdog";
const stop = watch("#root", {
onAdd: el => console.log("Added:", el),
onRemove: el => console.log("Removed:", el),
onChange: el => console.log("Changed:", el),
});
// To stop:
stop();import React, { useEffect } from "react";
import { watch } from "dom-watchdog";
export function ChatWatcher() {
useEffect(() => {
const stop = watch("#chat", {
onAdd: el => console.log("New message:", el.textContent),
});
return () => stop();
}, []);
return <div id="chat"></div>;
}watch(selector: string, options: WatchOptions, observerOptions?: MutationObserverInit): () => void-
selector:stringCSS selector of the parent element to be observed. -
options:WatchOptionsObject containing optional callbacks:-
onAdd(el: Element): Called when a new child element is added. -
onRemove(el: Element): Called when a child element is removed. -
onChange(el: Element): Called when:- an element's attribute is modified,
- or a node’s text content is changed.
-
-
observerOptions:MutationObserverInit(optional) Allows direct configuration of theMutationObserverbehavior. By default, the optionschildList,attributes, andsubtreeare set to true. To change this, override them using observerOptions.
- A function that, when called, disconnects the observer (
MutationObserver) and stops listening for changes.
dom-watchdog uses the native browser API MutationObserver to detect changes in the DOM.
This API allows monitoring:
- Addition or removal of elements
- Changes in element attributes
- Changes in text content
MutationObserver is supported by most modern browsers (+96%):
Can I use - MutationObserver
MIT © Jarod Cavalcante https://jarod.dev