MutationObserver Reacts To DOM Attribute Changes
Respond to late DOM writes with MutationObserver: subscribe to attribute and childList changes on a form, filter attributes, and disconnect on teardown.
Code
// MutationObserver: 表单被第三方脚本动态改写时被动监听,而不是轮询
const form = document.querySelector('#signup');
const observer = new MutationObserver((mutations) => {
for (const mutation of mutations) {
if (mutation.type === 'attributes') {
// 校验脚本改写 aria-invalid 时,同步错误提示
const field = mutation.target;
console.log('attr:', field.name, '->', field.getAttribute('aria-invalid'));
}
if (mutation.type === 'childList') {
console.log('fields changed, added:', mutation.addedNodes.length);
}
}
});
observer.observe(form, {
attributes: true,
attributeFilter: ['aria-invalid', 'disabled'], // 只订阅相关属性
childList: true,
subtree: true, // 属性变更发生在子树里的 input 上,subtree: false 时该分支永远收不到记录
});
(async () => {
// 某次校验之后:写入属性、插入字段——变更记录先进入待投递队列
form.querySelector('input[name=email]').setAttribute('aria-invalid', 'true');
form.appendChild(document.createElement('input'));
// MutationObserver 回调在微任务阶段才投递:若同步调用 disconnect
// 会清空待投递记录,回调永远不会执行——先让出一个宏任务,
// 上面两处变更的输出才会打印,之后再演示卸载清理
await new Promise((resolve) => setTimeout(resolve));
observer.disconnect(); // 组件卸载时停止观察,释放引用
})();How the snippet works
Iteration happens inside for (const mutation of mutations) — everything outside it runs once. Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.
Module-level bindings hold the data — form, observer — with no function scope in between.
What to watch for
- Uses
document, so it needs a browser context — it will not run as-is in Node without shims.
Using it
Expect labeled output — attr:, fields changed, added: — when the file runs.
Key statements
await new Promise((resolve) => setTimeout(resolve));
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- Does MutationObserver Reacts To DOM Attribute Changes run in plain Node.js?
- No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.