MutationObserver
MutationObserver watches for DOM changes: child additions/removals, attribute changes, and text content changes.
MutationObserver watches for DOM changes: child additions/removals, attribute changes, and text content changes.
const target = document.getElementById("dynamic-list");
const observer = new MutationObserver(mutations => {
mutations.forEach(m => {
if (m.type === "childList") {
console.log(`${m.addedNodes.length} nodes added`);
}
if (m.type === "attributes") {
console.log(`Attribute ${m.attributeName} changed`);
}
});
});
observer.observe(target, {
childList: true,
attributes: true,
subtree: true
});
Call observer.disconnect() when you no longer need to observe — it prevents memory leaks.