Mutation Observer

변형 관찰자

It batches notifications about DOM child, attribute, and text changes.

···
html
<div class="v"><header>MUTATION OBSERVER <span id="count">0 records</span></header><div class="stage mutations"><div id="nodes" class="nodes"><span>root</span></div><div class="log" id="log">watching childList</div></div><div class="muted">new node → mutation record</div></div>
css
.v{width:min(94vw,760px);height:min(88vh,320px);padding:clamp(9px,2.4vmin,18px);border:1px solid var(--line);border-radius:12px;background:var(--surface);font:500 clamp(12px,2.4vmin,16px)/1.3 var(--font-sans,system-ui,sans-serif);display:flex;flex-direction:column;gap:clamp(5px,1.4vmin,10px);overflow:hidden}.v header{display:flex;align-items:center;justify-content:space-between;gap:8px;color:var(--accent);font-weight:700}.v header span{color:var(--muted);font-weight:500}.v .stage{flex:1;min-height:0;position:relative}.v .muted{color:var(--muted)}.v .active{background:color-mix(in srgb,var(--accent) 18%,var(--surface));border-color:var(--accent)!important;color:var(--fg)}.v button{font:inherit;color:var(--fg);background:var(--bg);border:1px solid var(--line);border-radius:7px;padding:5px 8px;cursor:pointer}.mutations{display:flex;align-items:center;justify-content:space-around;gap:10px}.nodes,.log{width:45%;height:78%;border:1px solid var(--line);border-radius:8px;background:var(--bg);padding:8px;overflow:hidden}.nodes{display:flex;gap:5px;align-content:center;justify-content:center;flex-wrap:wrap}.nodes span{border:1px solid var(--accent);border-radius:5px;padding:4px 6px}.log{font-family:ui-monospace,monospace;color:var(--accent);display:flex;align-items:center}
js
const root=document.getElementById("nodes"),log=document.getElementById("log");let n=0;new MutationObserver(records=>{document.getElementById("count").textContent=records.length+" record";log.textContent="childList: +node "+n}).observe(root,{childList:true});function add(){n=n%4+1;root.innerHTML="<span>root</span>"+Array.from({length:n},(_,i)=>"<span>"+(i+1)+"</span>").join("")}add();setInterval(add,900)

Mutation Observer delivers records of changes in a selected DOM area. You choose whether to watch children, attributes, or text.

In the demo, adding a node appends a record to the log. Watching too broad a subtree can produce unnecessary records, so narrow the target and options.

When to use

Use it to detect third-party DOM changes or synchronize an editor.

Open as page ↗