Auto Number Headings with MutationObserver
JavaScript
Hard
3 views
Problem Description
You have a container #article where headings are
. Prefix each heading text with its number like '1. Title'. If headings change later, auto re-number.
Output Format
No output (DOM change).
Constraints
Assume #article exists and headings are h2 inside it.
Official Solution
const root=document.getElementById('article');const apply=()=>{const hs=[...root.querySelectorAll('h2')];for(let i=0;i<hs.length;i++){const h=hs[i];const raw=h.getAttribute('data-raw')||h.textContent.replace(/^\\d+\\.\\s*/,'');h.setAttribute('data-raw',raw);h.textContent=(i+1)+'. '+raw;}};apply();const mo=new MutationObserver(()=>apply());mo.observe(root,{childList:true,subtree:true,characterData:true});
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!