Mutation Observer는 DOM의 선택한 영역에서 일어난 변경을 기록으로 전달합니다. 자식 추가, 속성 변경, 텍스트 변경 중 필요한 종류를 지정해 관찰합니다.
데모에서는 노드가 추가될 때마다 관찰 로그에 기록이 쌓입니다. 관찰 범위를 너무 넓히면 불필요한 기록이 많아질 수 있어 대상과 옵션을 좁히는 편이 좋습니다.
언제 쓰나
외부 스크립트가 DOM을 바꾸는 시점을 감지하거나 편집기 동기화를 구현할 때 씁니다.
DOM의 자식·속성·텍스트 변경을 모아서 알립니다.
<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>.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}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는 DOM의 선택한 영역에서 일어난 변경을 기록으로 전달합니다. 자식 추가, 속성 변경, 텍스트 변경 중 필요한 종류를 지정해 관찰합니다.
데모에서는 노드가 추가될 때마다 관찰 로그에 기록이 쌓입니다. 관찰 범위를 너무 넓히면 불필요한 기록이 많아질 수 있어 대상과 옵션을 좁히는 편이 좋습니다.
외부 스크립트가 DOM을 바꾸는 시점을 감지하거나 편집기 동기화를 구현할 때 씁니다.