[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"verticals":3,"quiz-mutation-observer-dom-change-detection":32,"quiz-article-mutation-observer-dom-change-detection":48},[4,20],{"id":5,"slug":6,"name":7,"tagline":8,"description":9,"accentFrom":10,"accentTo":11,"icon":12,"defaultLocale":13,"locales":14,"features":16,"position":19},"019fe637-3d33-714b-b57f-23e163ffca0c","dev","Web Development","Build. Learn. Ship.","Practical courses, engineering-grade articles and open-source tools for people who ship.","violet-500","cyan-400","◇","en",[13,15],"fa",{"courses":17,"paths":17,"articles":17,"exams":18,"flashcards":18,"packages":17,"community":17,"certificates":17,"teams":17,"commerce":17},true,false,0,{"id":21,"slug":22,"name":23,"tagline":24,"description":25,"accentFrom":26,"accentTo":10,"icon":27,"defaultLocale":13,"locales":28,"features":30,"position":31},"019fe637-3dc2-754c-8657-0f175bfee7c6","lang","Languages","Learn a language the way you learn a codebase.","Structured paths, listening drills and spaced repetition that actually sticks.","amber-400","⌘",[13,15,29],"es",{"courses":17,"paths":17,"articles":18,"exams":18,"flashcards":18,"packages":18,"community":17,"certificates":18,"teams":18,"commerce":17},2,{"id":33,"slug":34,"kind":35,"title":36,"description":37,"config":38,"verticalId":5,"vertical":43,"course":40,"_count":44,"access":45,"attempts":47,"questionCount":39},"019ff19b-f6c2-7399-adec-2ec63e233f15","mutation-observer-dom-change-detection","PRACTICE_QUIZ","MutationObserver — DOM change detection","MutationObserver watches for changes to the DOM — child node additions\u002Fremovals, attribute edits, and text content changes — and delivers them as a batch after each synchronous operation. These questions cover the observer's configuration options, what a MutationRecord contains, batching behavior, teardown, and how it compares to the setInterval polling pattern.",{"questionCount":39,"timeLimitSec":40,"shuffleQuestions":18,"shuffleOptions":17,"negativeMarking":19,"passScorePct":41,"maxAttempts":40,"revealAnswers":42,"allowFlagging":18,"allowBacktracking":17},9,null,70,"AFTER_SUBMIT",{"slug":6,"name":7},{"questions":39},{"allowed":17,"reason":46},"FREE",[],{"id":49,"slug":34,"title":50,"subtitle":40,"excerpt":51,"coverUrl":52,"locale":13,"readingMinutes":53,"publishedAt":54,"viewCount":55,"likeCount":19,"commentCount":19,"author":56,"vertical":61,"topic":62,"tags":65,"_count":77,"playground":79,"body":81,"bodyMd":212,"seo":213,"translationGroupId":217,"thread":218,"assessments":220,"translations":223,"quiz":225},"019ff19b-f68d-77ea-9a2c-70e14c5c7a05","You're polling setInterval to detect DOM changes. `MutationObserver` fires when they happen.","Watching for DOM mutations with setInterval or custom event dispatch is fragile and imprecise. The MutationObserver API delivers a callback exactly when attributes, text content, or child elements change — with full control over which types of mutations you watch.","\u002Fmedia\u002Fcovers\u002Fmutation-observer-dom-change-detection.png",4,"2026-08-11T15:48:01.781Z",114,{"id":57,"name":58,"username":59,"avatarUrl":40,"headline":60},"019fe637-3c25-7088-9034-39c9f15dc3c8","Parsa Jiravand","parsa","Frontend engineer · building bestpractic",{"slug":6,"name":7,"accentFrom":10,"accentTo":11},{"slug":63,"name":64},"javascript","JavaScript",[66,68,71,74],{"slug":63,"name":67,"color":40},"Javascript",{"slug":69,"name":70,"color":40},"webdev","Webdev",{"slug":72,"name":73,"color":40},"frontend","Frontend",{"slug":75,"name":76,"color":40},"dom","Dom",{"assessments":78},1,{"slug":34,"title":80},"MutationObserver — interactive playground",{"blocks":82,"version":78},[83,87,91,97,100,103,106,110,113,117,120,123,126,129,133,136,140,143,146,149,156,159,162,165,168,171,174,177,180,183,186,189,192,195,198,201,204],{"id":84,"html":85,"type":86},"b1","\u003Cp>The DOM can change in ways your code didn&#39;t trigger — a third-party widget injects a node, a library adds a class, a rich text editor updates its content. The common response is polling: \u003Ccode>setInterval(() =&gt; checkIfThingChanged(), 100)\u003C\u002Fcode>. It works until it doesn&#39;t. You tune the interval, miss changes that happen between ticks, and pay CPU cost whether anything changes or not. \u003Ccode>MutationObserver\u003C\u002Fcode> is the built-in answer.\u003C\u002Fp>","paragraph",{"id":88,"html":89,"text":89,"type":90,"level":31},"b2","The API","heading",{"id":92,"code":93,"type":94,"language":95,"highlight":96},"b3","const observer = new MutationObserver((mutations) => {\n  for (const mutation of mutations) {\n    console.log(mutation.type);         \u002F\u002F 'attributes' | 'characterData' | 'childList'\n    console.log(mutation.target);       \u002F\u002F the node that changed\n    console.log(mutation.addedNodes);   \u002F\u002F NodeList (for childList mutations)\n    console.log(mutation.oldValue);     \u002F\u002F previous value (if requested)\n  }\n});\n\nobserver.observe(document.getElementById('app'), {\n  childList: true,              \u002F\u002F watch for added\u002Fremoved child nodes\n  subtree: true,                \u002F\u002F include all descendants, not just direct children\n  attributes: true,             \u002F\u002F watch attribute changes\n  characterData: true,          \u002F\u002F watch text node content changes\n  attributeOldValue: true,      \u002F\u002F record the previous attribute value\n  characterDataOldValue: true,  \u002F\u002F record the previous text content\n});\n\n\u002F\u002F Stop watching:\nobserver.disconnect();","code","js",[],{"id":98,"html":99,"type":86},"b4","\u003Cp>Two steps: create an observer with a callback, then call \u003Ccode>.observe(node, options)\u003C\u002Fcode>. The callback fires asynchronously after a batch of mutations completes — never mid-update — with an array of \u003Ccode>MutationRecord\u003C\u002Fcode> objects, one per change.\u003C\u002Fp>",{"id":101,"html":102,"text":102,"type":90,"level":31},"b5","What it replaces",{"id":104,"html":105,"type":86},"b6","\u003Cp>Here&#39;s the typical &quot;wait for a class to appear&quot; pattern using an interval:\u003C\u002Fp>",{"id":107,"code":108,"type":94,"language":95,"highlight":109},"b7","\u002F\u002F Before — fragile, always running\nlet seen = false;\nconst timer = setInterval(() => {\n  const el = document.querySelector('.widget-loaded');\n  if (el && !seen) {\n    seen = true;\n    clearInterval(timer);\n    initWidget(el);\n  }\n}, 50);",[],{"id":111,"html":112,"type":86},"b8","\u003Cp>The 50 ms interval means you catch changes up to 50 ms late, it burns CPU on every tick even when nothing is happening, and if you forget to \u003Ccode>clearInterval\u003C\u002Fcode>, it runs indefinitely. With \u003Ccode>MutationObserver\u003C\u002Fcode>:\u003C\u002Fp>",{"id":114,"code":115,"type":94,"language":95,"highlight":116},"b9","\u002F\u002F After — fires immediately when the node appears\nconst observer = new MutationObserver(() => {\n  const el = document.querySelector('.widget-loaded');\n  if (el) {\n    observer.disconnect();\n    initWidget(el);\n  }\n});\n\nobserver.observe(document.body, { childList: true, subtree: true });",[],{"id":118,"html":119,"type":86},"b10","\u003Cp>No timer, no polling overhead, no missed windows.\u003C\u002Fp>",{"id":121,"html":122,"text":122,"type":90,"level":31},"b11","Real-world use cases",{"id":124,"html":125,"type":86},"b12","\u003Cp>\u003Cstrong>Third-party widget lifecycle.\u003C\u002Fstrong> When you embed a chat widget or payment form from a third party, you have no hook into when it finishes rendering. \u003Ccode>MutationObserver\u003C\u002Fcode> on the container gives you that hook without touching the third-party script.\u003C\u002Fp>",{"id":127,"html":128,"type":86},"b13","\u003Cp>\u003Cstrong>Auto-resizing a textarea.\u003C\u002Fstrong> The \u003Ccode>input\u003C\u002Fcode> event doesn&#39;t fire on programmatic changes. Observing \u003Ccode>characterData\u003C\u002Fcode> on the textarea&#39;s text node catches every content change regardless of source:\u003C\u002Fp>",{"id":130,"code":131,"type":94,"language":95,"highlight":132},"b14","function autoResize(textarea) {\n  const resize = () => {\n    textarea.style.height = 'auto';\n    textarea.style.height = `${textarea.scrollHeight}px`;\n  };\n\n  resize();\n\n  const observer = new MutationObserver(resize);\n  observer.observe(textarea, { characterData: true, subtree: true });\n  textarea.addEventListener('input', resize);\n\n  return () => observer.disconnect();\n}",[],{"id":134,"html":135,"type":86},"b15","\u003Cp>\u003Cstrong>Accessible live announcements.\u003C\u002Fstrong> Screen readers miss DOM updates that don&#39;t go through an \u003Ccode>aria-live\u003C\u002Fcode> region. A \u003Ccode>MutationObserver\u003C\u002Fcode> on a dynamic feed can forward new content to an announcer element, making additions audible without a framework:\u003C\u002Fp>",{"id":137,"code":138,"type":94,"language":95,"highlight":139},"b16","const announcer = document.getElementById('sr-announcer'); \u002F\u002F aria-live=\"polite\"\n\nconst observer = new MutationObserver((mutations) => {\n  for (const mutation of mutations) {\n    for (const node of mutation.addedNodes) {\n      if (node.textContent?.trim()) {\n        announcer.textContent = node.textContent.trim();\n      }\n    }\n  }\n});\n\nobserver.observe(document.getElementById('feed'), { childList: true });",[],{"id":141,"html":142,"text":142,"type":90,"level":31},"b17","Batching and performance",{"id":144,"html":145,"type":86},"b18","\u003Cp>\u003Ccode>MutationObserver\u003C\u002Fcode> delivers changes in batches. If a loop adds 500 nodes in one synchronous operation, you get one callback with 500 records — not 500 callbacks. This is intentional: the observer is low-overhead even on large, active DOM trees.\u003C\u002Fp>",{"id":147,"html":148,"type":86},"b19","\u003Cp>A few things to keep in mind:\u003C\u002Fp>",{"id":150,"type":151,"items":152,"ordered":18},"b20","list",[153,154,155],"\u003Cstrong>Narrow the target.\u003C\u002Fstrong> Observing \u003Ccode>document.body\u003C\u002Fcode> with \u003Ccode>subtree: true\u003C\u002Fcode> watches every node in the page. Prefer the smallest relevant container.","\u003Cstrong>Always disconnect.\u003C\u002Fstrong> The observer holds a reference to the target node, which can delay garbage collection. Call \u003Ccode>observer.disconnect()\u003C\u002Fcode> when you&#39;re done.","\u003Cstrong>\u003Ccode>takeRecords()\u003C\u002Fcode> for early cleanup.\u003C\u002Fstrong> This flushes any pending, undelivered records synchronously — useful when you need to process remaining mutations before disconnecting without waiting for the next callback.",{"id":157,"html":158,"text":158,"type":90,"level":31},"b21","Browser support",{"id":160,"html":161,"type":86},"b22","\u003Cp>\u003Ccode>MutationObserver\u003C\u002Fcode> is \u003Cstrong>Baseline 2015\u003C\u002Fstrong>: Chrome 26 (2013), Firefox 14 (2012), Safari 7 (2013). It has shipped in every major browser and runtime for over a decade, including Web Workers.\u003C\u002Fp>",{"id":163,"html":164,"type":86},"b23","\u003C!-- playground:start -->",{"id":166,"html":167,"text":167,"type":90,"level":31},"b24","🎮 Try it yourself",{"id":169,"html":170,"type":86},"b25","\u003Cp>\u003Cstrong>\u003Ca href=\"https:\u002F\u002Fdaily-post-dev.netlify.app\u002Fposts\u002F2026-08-11-mutation-observer-dom-change-detection\u002Fplayground\u002F\">▶️ Open the interactive playground →\u003C\u002Fa>\u003C\u002Fstrong>\u003C\u002Fp>",{"id":172,"html":173,"type":86},"b26","\u003Cp>\u003Cem>Runs right in your browser — poke at it and watch the concept react live.\u003C\u002Fem>\u003C\u002Fp>",{"id":175,"html":176,"type":86},"b27","\u003C!-- playground:end -->",{"id":178,"html":179,"type":86},"b28","\u003C!-- quiz:start -->",{"id":181,"html":182,"text":182,"type":90,"level":31},"b29","🧠 Test yourself",{"id":184,"html":185,"type":86},"b30","\u003Cp>Think it clicked? \u003Cstrong>\u003Ca href=\"https:\u002F\u002Fdaily-post-dev.netlify.app\u002Fquiz\u002Ftake.html?post=2026-08-11-mutation-observer-dom-change-detection\">Take the 9-question quiz →\u003C\u002Fa>\u003C\u002Fstrong>\u003C\u002Fp>",{"id":187,"html":188,"type":86},"b31","\u003Cp>\u003Cem>Instant feedback, a hint on every question, and an explanation for each answer — right or wrong.\u003C\u002Fem>\u003C\u002Fp>",{"id":190,"html":191,"type":86},"b32","\u003C!-- quiz:end -->",{"id":193,"html":194,"text":194,"type":90,"level":31},"b33","The takeaway",{"id":196,"html":197,"type":86},"b34","\u003Cp>Search your codebase for \u003Ccode>setInterval\u003C\u002Fcode> calls that check a DOM condition and clear themselves once it&#39;s true — that&#39;s polling for a DOM change. \u003Ccode>MutationObserver\u003C\u002Fcode> replaces the pattern with a callback that fires the moment the change occurs, with zero cost in between. It completes the browser&#39;s built-in observer trio: \u003Ccode>IntersectionObserver\u003C\u002Fcode> for element visibility, \u003Ccode>ResizeObserver\u003C\u002Fcode> for element size, and \u003Ccode>MutationObserver\u003C\u002Fcode> for everything the DOM itself changes. Once you know all three, most &quot;watch the DOM&quot; problems reduce to picking the right one.\u003C\u002Fp>",{"id":199,"type":200},"b35","divider",{"id":202,"html":203,"type":86},"b36","\u003Cp>\u003Cem>Thanks for reading! Let&#39;s stay connected:\u003C\u002Fem>\u003C\u002Fp>",{"id":205,"type":151,"items":206,"ordered":18},"b37",[207,208,209,210,211],"⭐ \u003Cstrong>GitHub\u003C\u002Fstrong> — follow me and star the projects: \u003Ca href=\"https:\u002F\u002Fgithub.com\u002Fparsajiravand\">github.com\u002Fparsajiravand\u003C\u002Fa>","💬 \u003Cstrong>Discord\u003C\u002Fstrong> — join the frontend best-practices community: \u003Ca href=\"https:\u002F\u002Fdiscord.gg\u002Fd9KRhuAwQ\">discord.gg\u002Fd9KRhuAwQ\u003C\u002Fa>","📸 \u003Cstrong>Instagram\u003C\u002Fstrong> — frontend best practices, daily: \u003Ca href=\"https:\u002F\u002Fwww.instagram.com\u002Fbestpractice___\u002F\">@bestpractice___\u003C\u002Fa>","💼 \u003Cstrong>LinkedIn\u003C\u002Fstrong> — \u003Ca href=\"https:\u002F\u002Fwww.linkedin.com\u002Fin\u002Fparsa-jiravand\u002F\">linkedin.com\u002Fin\u002Fparsa-jiravand\u003C\u002Fa>","✉️ \u003Cstrong>Email\u003C\u002Fstrong> (work &amp; contract inquiries): \u003Ca href=\"mailto:bestpractice2026@gmail.com\">bestpractice2026@gmail.com\u003C\u002Fa>","The DOM can change in ways your code didn't trigger — a third-party widget injects a node, a library adds a class, a rich text editor updates its content. The common response is polling: `setInterval(() => checkIfThingChanged(), 100)`. It works until it doesn't. You tune the interval, miss changes that happen between ticks, and pay CPU cost whether anything changes or not. `MutationObserver` is the built-in answer.\n\n## The API\n\n```js\nconst observer = new MutationObserver((mutations) => {\n  for (const mutation of mutations) {\n    console.log(mutation.type);         \u002F\u002F 'attributes' | 'characterData' | 'childList'\n    console.log(mutation.target);       \u002F\u002F the node that changed\n    console.log(mutation.addedNodes);   \u002F\u002F NodeList (for childList mutations)\n    console.log(mutation.oldValue);     \u002F\u002F previous value (if requested)\n  }\n});\n\nobserver.observe(document.getElementById('app'), {\n  childList: true,              \u002F\u002F watch for added\u002Fremoved child nodes\n  subtree: true,                \u002F\u002F include all descendants, not just direct children\n  attributes: true,             \u002F\u002F watch attribute changes\n  characterData: true,          \u002F\u002F watch text node content changes\n  attributeOldValue: true,      \u002F\u002F record the previous attribute value\n  characterDataOldValue: true,  \u002F\u002F record the previous text content\n});\n\n\u002F\u002F Stop watching:\nobserver.disconnect();\n```\n\nTwo steps: create an observer with a callback, then call `.observe(node, options)`. The callback fires asynchronously after a batch of mutations completes — never mid-update — with an array of `MutationRecord` objects, one per change.\n\n## What it replaces\n\nHere's the typical \"wait for a class to appear\" pattern using an interval:\n\n```js\n\u002F\u002F Before — fragile, always running\nlet seen = false;\nconst timer = setInterval(() => {\n  const el = document.querySelector('.widget-loaded');\n  if (el && !seen) {\n    seen = true;\n    clearInterval(timer);\n    initWidget(el);\n  }\n}, 50);\n```\n\nThe 50 ms interval means you catch changes up to 50 ms late, it burns CPU on every tick even when nothing is happening, and if you forget to `clearInterval`, it runs indefinitely. With `MutationObserver`:\n\n```js\n\u002F\u002F After — fires immediately when the node appears\nconst observer = new MutationObserver(() => {\n  const el = document.querySelector('.widget-loaded');\n  if (el) {\n    observer.disconnect();\n    initWidget(el);\n  }\n});\n\nobserver.observe(document.body, { childList: true, subtree: true });\n```\n\nNo timer, no polling overhead, no missed windows.\n\n## Real-world use cases\n\n**Third-party widget lifecycle.** When you embed a chat widget or payment form from a third party, you have no hook into when it finishes rendering. `MutationObserver` on the container gives you that hook without touching the third-party script.\n\n**Auto-resizing a textarea.** The `input` event doesn't fire on programmatic changes. Observing `characterData` on the textarea's text node catches every content change regardless of source:\n\n```js\nfunction autoResize(textarea) {\n  const resize = () => {\n    textarea.style.height = 'auto';\n    textarea.style.height = `${textarea.scrollHeight}px`;\n  };\n\n  resize();\n\n  const observer = new MutationObserver(resize);\n  observer.observe(textarea, { characterData: true, subtree: true });\n  textarea.addEventListener('input', resize);\n\n  return () => observer.disconnect();\n}\n```\n\n**Accessible live announcements.** Screen readers miss DOM updates that don't go through an `aria-live` region. A `MutationObserver` on a dynamic feed can forward new content to an announcer element, making additions audible without a framework:\n\n```js\nconst announcer = document.getElementById('sr-announcer'); \u002F\u002F aria-live=\"polite\"\n\nconst observer = new MutationObserver((mutations) => {\n  for (const mutation of mutations) {\n    for (const node of mutation.addedNodes) {\n      if (node.textContent?.trim()) {\n        announcer.textContent = node.textContent.trim();\n      }\n    }\n  }\n});\n\nobserver.observe(document.getElementById('feed'), { childList: true });\n```\n\n## Batching and performance\n\n`MutationObserver` delivers changes in batches. If a loop adds 500 nodes in one synchronous operation, you get one callback with 500 records — not 500 callbacks. This is intentional: the observer is low-overhead even on large, active DOM trees.\n\nA few things to keep in mind:\n\n- **Narrow the target.** Observing `document.body` with `subtree: true` watches every node in the page. Prefer the smallest relevant container.\n- **Always disconnect.** The observer holds a reference to the target node, which can delay garbage collection. Call `observer.disconnect()` when you're done.\n- **`takeRecords()` for early cleanup.** This flushes any pending, undelivered records synchronously — useful when you need to process remaining mutations before disconnecting without waiting for the next callback.\n\n## Browser support\n\n`MutationObserver` is **Baseline 2015**: Chrome 26 (2013), Firefox 14 (2012), Safari 7 (2013). It has shipped in every major browser and runtime for over a decade, including Web Workers.\n\n\n\u003C!-- playground:start -->\n\n## 🎮 Try it yourself\n\n**[▶️ Open the interactive playground →](https:\u002F\u002Fdaily-post-dev.netlify.app\u002Fposts\u002F2026-08-11-mutation-observer-dom-change-detection\u002Fplayground\u002F)**\n\n_Runs right in your browser — poke at it and watch the concept react live._\n\n\u003C!-- playground:end -->\n\n\u003C!-- quiz:start -->\n\n## 🧠 Test yourself\n\nThink it clicked? **[Take the 9-question quiz →](https:\u002F\u002Fdaily-post-dev.netlify.app\u002Fquiz\u002Ftake.html?post=2026-08-11-mutation-observer-dom-change-detection)**\n\n_Instant feedback, a hint on every question, and an explanation for each answer — right or wrong._\n\n\u003C!-- quiz:end -->\n## The takeaway\n\nSearch your codebase for `setInterval` calls that check a DOM condition and clear themselves once it's true — that's polling for a DOM change. `MutationObserver` replaces the pattern with a callback that fires the moment the change occurs, with zero cost in between. It completes the browser's built-in observer trio: `IntersectionObserver` for element visibility, `ResizeObserver` for element size, and `MutationObserver` for everything the DOM itself changes. Once you know all three, most \"watch the DOM\" problems reduce to picking the right one.\n\n---\n\n*Thanks for reading! Let's stay connected:*\n\n- ⭐ **GitHub** — follow me and star the projects: [github.com\u002Fparsajiravand](https:\u002F\u002Fgithub.com\u002Fparsajiravand)\n- 💬 **Discord** — join the frontend best-practices community: [discord.gg\u002Fd9KRhuAwQ](https:\u002F\u002Fdiscord.gg\u002Fd9KRhuAwQ)\n- 📸 **Instagram** — frontend best practices, daily: [@bestpractice___](https:\u002F\u002Fwww.instagram.com\u002Fbestpractice___\u002F)\n- 💼 **LinkedIn** — [linkedin.com\u002Fin\u002Fparsa-jiravand](https:\u002F\u002Fwww.linkedin.com\u002Fin\u002Fparsa-jiravand\u002F)\n- ✉️ **Email** (work & contract inquiries): [bestpractice2026@gmail.com](mailto:bestpractice2026@gmail.com)",{"title":214,"canonical":215,"description":216},"You're polling setInterval to detect DOM changes. `MutationObserver` f","https:\u002F\u002Fbestpractic.org\u002Fblog\u002Fmutation-observer-dom-change-detection","Watching for DOM mutations with setInterval or custom event dispatch is fragile and imprecise. The MutationObserver API delivers a callback exactly when attributes, text content, o","019ff19b-f68d-77ea-9a2c-7638a5552195",{"id":219,"locked":18},"019ff19b-f6a7-740e-82a3-f42d6837c361",[221],{"id":33,"slug":34,"title":36,"_count":222},{"questions":39},[224],{"locale":13,"slug":34},{"id":33,"slug":34,"title":36,"_count":226,"questionCount":39},{"questions":39}]