A table of contents is helpful when it reflects the article’s real structure. It should be generated from the same headings that render in the article, rather than maintained as a second list that can drift.
Generate stable targets
Choose which heading levels belong in the navigation, usually section headings and optionally one nested level. Derive an ID from the heading text, normalize it consistently, and handle duplicates by adding a deterministic suffix. If headings can be edited frequently, consider storing an explicit anchor identifier so a text change does not break shared links.
Do not create IDs from untrusted HTML or allow arbitrary attributes through a Markdown renderer. Keep the heading text as the accessible link name. The navigation itself should be a labeled
navAccount for browser behavior
Fixed headers can cover an anchor after navigation. Use scroll margin on heading targets and test both direct page loads with a fragment and clicks from the table of contents. Avoid custom scroll code unless native fragment navigation cannot meet the requirement. If the active item is tracked while scrolling, use an observer that disconnects on unmount and ensure it does not steal focus.
Skip the table of contents for short articles with only a couple of sections. Test duplicate headings, punctuation, non-Latin text, heading edits, keyboard use, and narrow screens. A useful contents list reduces navigation effort; an auto-generated list of every heading can become clutter.
Build anchors from the same parsed document
CommonMark recognizes ATX headings such as a line starting with two hash marks. It also recognizes Setext headings and fenced code blocks. A line-by-line search for hash marks can count headings inside code, miss Setext headings, and produce mismatched anchors. Build the outline from the rendered heading nodes or from the same parsed tree that renders them. CommonMark heading and block rules
Test a document with two headings named “Setup,” one heading styled with inline code, and a fenced block that looks like a heading. Give repeated headings unique identifiers in document order. If the system promises long-lived deep links, store published identifiers or aliases so later changes to heading text leave the existing links resolvable. Place the resulting links in a labeled navigation landmark and check where focus and scroll land when a reader follows one.
Worked example
The output is heading-setup-0 and heading-setup-1. Generate the table of contents and rendered heading IDs from the same parsed heading sequence; skip code fences.
jsconst counts = new Map(); function headingId(text) { const base = text.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, ""); const count = counts.get(base) ?? 0; counts.set(base, count + 1); return `heading-${base || "section"}-${count}`; } console.log(headingId("Setup"), headingId("Setup"));




Community
Discussion
Loading comments…