Walk the DOM in document order and collect the headings (H1–H6) with their level and textContent. Then nest them with a stack: pop while the top of the stack has the same or a deeper level, attach the heading to whatever is left on top (or to the root), and push it. That handles skipped levels (an h4 under an h2) without breaking the tree. Give every heading a unique, URL-safe id (keep existing ids so old links work), and render nested <ol> links with escaped text, optionally limited to a level range such as h2–h3.
Generate table of contents/outline from a HTML page (similar to Google Docs autogenerated outline).
Answer it out loud, in your own words. Then compare.
Interviewers listen for how you get there, not only where you land. The answer opens once you have tried.
A depth-first walk visits elements in document order. A regex on tagName (/^H([1-6])$/) finds headings and gives the level; textContent includes the text of nested elements like <code>. The checks run on a stand-in for elements with only tagName, id, textContent and children.
// Every heading (h1-h6) under the root, in document order, with its level and text.function headings(root) {const out = [];const visit = (node) => {for (const child of node.children) {const m = /^H([1-6])$/.exec(child.tagName);if (m) out.push({ level: Number(m[1]), text: child.textContent.trim(), element: child });visit(child);}};visit(root);return out;}
passes 3 checks run on every build, against the native method where there is one
- finds every heading in document order, with level and text
- text includes nested elements and is trimmed
- a page with no headings gives []
The stack holds the current path of open sections. For each heading, pop everything at the same or a deeper level, attach to the top, push. A document that starts with an h3, or jumps from h2 to h4, still produces a sensible tree. For links, each heading needs an id: keep one it already has, otherwise slug the text (lower case, accents removed, non-alphanumerics to -) and add -1, -2 for repeats, the way GitHub does for README headings.
// Every heading (h1-h6) under the root, in document order, with its level and text.function headings(root) {const out = [];const visit = (node) => {for (const child of node.children) {const m = /^H([1-6])$/.exec(child.tagName);if (m) out.push({ level: Number(m[1]), text: child.textContent.trim(), element: child });visit(child);}};visit(root);return out;}// URL-safe ids from the text, made unique on the page: setup, setup-1, setup-2…function slugger() {const used = new Set();return (text, existing) => {if (existing && !used.has(existing)) {used.add(existing);return existing; // an id already in the page is kept, so old links still work}const base = text.toLowerCase().normalize('NFKD').replace(/[\u0300-\u036f]/g, '').replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'section';let slug = base;for (let n = 1; used.has(slug); n++) slug = `${base}-${n}`;used.add(slug);return slug;};}// Nest by level with a stack. A heading goes under the nearest earlier heading of a lower level,// so a skipped level (h2 then h4) still nests instead of breaking the tree.function toc(root) {const slug = slugger();const tree = [];const stack = []; // the current path of open sectionsfor (const h of headings(root)) {const item = { level: h.level, text: h.text, id: slug(h.text, h.element.id), children: [] };while (stack.length && stack[stack.length - 1].level >= h.level) stack.pop();(stack.length ? stack[stack.length - 1].children : tree).push(item);stack.push(item);}return tree;}
passes 4 checks run on every build, against the native method where there is one
- nests by level, including a skipped level
- ids: existing ones kept, others slugged and made unique
- slugs drop accents and punctuation
- a document that starts deeper still builds a tree
Recursively render nested <ol> with numbered links (1, 1.1, 1.2). Heading text is user content, so escape it; ids go through encodeURIComponent in the href. Real tables of contents usually show h2–h3: headings above the range (the page title) are skipped but their children kept, and deeper ones are dropped. Wrap it in a <nav> with a label so screen readers can jump to it.
// Every heading (h1-h6) under the root, in document order, with its level and text.function headings(root) {const out = [];const visit = (node) => {for (const child of node.children) {const m = /^H([1-6])$/.exec(child.tagName);if (m) out.push({ level: Number(m[1]), text: child.textContent.trim(), element: child });visit(child);}};visit(root);return out;}// URL-safe ids from the text, made unique on the page: setup, setup-1, setup-2…function slugger() {const used = new Set();return (text, existing) => {if (existing && !used.has(existing)) {used.add(existing);return existing; // an id already in the page is kept, so old links still work}const base = text.toLowerCase().normalize('NFKD').replace(/[\u0300-\u036f]/g, '').replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'section';let slug = base;for (let n = 1; used.has(slug); n++) slug = `${base}-${n}`;used.add(slug);return slug;};}// Nest by level with a stack. A heading goes under the nearest earlier heading of a lower level,// so a skipped level (h2 then h4) still nests instead of breaking the tree.function toc(root) {const slug = slugger();const tree = [];const stack = []; // the current path of open sectionsfor (const h of headings(root)) {const item = { level: h.level, text: h.text, id: slug(h.text, h.element.id), children: [] };while (stack.length && stack[stack.length - 1].level >= h.level) stack.pop();(stack.length ? stack[stack.length - 1].children : tree).push(item);stack.push(item);}return tree;}const ESC = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };const escapeHtml = (s) => s.replace(/[&<>"']/g, (c) => ESC[c]);// Render nested <ol> links, numbered 1, 1.1, 1.2… Only levels in [from, to] are shown (often h2-h3):// deeper items are dropped, shallower ones (the page title) are skipped but their children kept.function renderToc(tree, { from = 1, to = 6 } = {}) {const shown = (items) =>items.flatMap((item) => {if (item.level < from) return shown(item.children);if (item.level > to) return [];return [{ ...item, children: shown(item.children) }];});const list = (items, prefix) =>items.length === 0? '': '<ol>' +items.map((item, i) => {const number = prefix + (i + 1);return `<li><a href="#${encodeURIComponent(item.id)}">${number} ${escapeHtml(item.text)}</a>${list(item.children, number + '.')}</li>`;}).join('') +'</ol>';return `<nav aria-label="Table of contents">${list(shown(tree), '')}</nav>`;}
passes 4 checks run on every build, against the native method where there is one
- renders numbered, nested links
- heading text is escaped
- a level range skips the title and drops deep items
- an empty page renders an empty nav
Docs sites and READMEs
GitHub, MDN and Docusaurus build the "On this page" box exactly this way: collect headings, slug them into ids (with -1, -2 for duplicates), and link to #id.
Highlighting the current section
An IntersectionObserver on the headings tells you which section is on screen, so the matching link can be marked as current while the reader scrolls, without listening to scroll.
Headings are an accessibility outline
Screen-reader users jump between headings. A skipped level in the page shows up as a jump in the generated table of contents, which is a quick way to spot heading structure problems.
Nesting by
level - 1without a stack, which breaks when a level is skipped.Duplicate ids when two headings share a title, so both links jump to the first one.
Overwriting ids the page already has, which breaks links people have shared.
Inserting heading text into HTML unescaped.
Using
innerTextin a walk over many headings: it triggers layout for each one;textContentdoesn't.
How would you keep the TOC in sync when content changes?
Rebuild it from a MutationObserver on the article (childList and characterData, with subtree: true), debounced so a burst of edits rebuilds once.
Why textContent and not innerText?
innerText depends on CSS (it skips hidden text) and forces a layout to compute it; textContent is just the text in the tree, which is what a heading's label should be and costs nothing extra.
What's the complexity?
One walk over the DOM is O(n) elements, and nesting is O(h) for h headings, since every heading is pushed and popped at most once.
- developer.mozilla.org/en-US/docs/Web/HTML/Element/Heading_Elements
- developer.mozilla.org/en-US/docs/Web/API/Node/textContent
- developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize
- developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent