Observe DOM mutations
Quick answer
MutationObserver reports matching mutation records asynchronously. observe configures which mutations to watch; disconnect stops observation and discards queued records. Use takeRecords if you need to retrieve pending records directly.
Browser example
Run in a browser document, not a bare Node.js process.
const e=document.createElement("div");const o=new MutationObserver(()=>{});o.observe(e,{childList:true});e.append(document.createElement("p"));console.log(o.takeRecords().length);o.disconnect();Expected console output:
1Common mistake
Do not assume observer callbacks run synchronously inside append.
Practice
Observe attributes only, change one attribute and inspect the record type.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Observe DOM mutations — Knowledge Check
Check the central concept, apply it to a new scenario, and predict browser behavior.
Which method retrieves and clears queued mutation records?
Which option should you set to monitor attribute changes?
When is a mutation observer callback normally delivered relative to append?
What happens to queued records when disconnect is called without first retrieving them?
What is printed by this browser snippet? (Observe DOM mutations)
const e=document.createElement("div");const o=new MutationObserver(()=>{});o.observe(e,{attributes:true});e.setAttribute("data-status","ready");console.log(o.takeRecords()[0].type,o.takeRecords().length);o.disconnect();