Documentation pages, blog posts and long settings screens show a table of contents: a nested list of links to the page's headings. Building one in the browser means finding the headings, nesting them by level (an h3 under the h2 before it), and making sure every heading has an id the links can point to: readable, and unique in the page.
functionbuildToc(root) // returns an array of entriesfunctionrenderToc(items) // returns a <ul> element
buildToc(root): reads the h1–h6 headings inside root and returns the top-level entries. Each entry is { id, text, level, children }, where level is the heading's number (2 for h2) and children holds the entries under it. Headings without an id get one.
renderToc(items): turns entries into a <ul> with one <li><a href="#id">text</a></li> per entry, and a nested <ul> inside the <li> when the entry has children.
Every h1–h6 inside root, at any depth, in document order, becomes an entry. Other elements (header, hr, role="heading") do not, and nothing outside root does.
A heading goes under the nearest earlier heading with a smaller level, even if levels are skipped (h2 then h4). With no such heading, it is a top-level entry.
text is the heading's text content with every run of whitespace turned into one space and the ends trimmed. Headings whose text is empty are left out and get no id.
A heading that has an id keeps it. One without gets an id made from its text: lower case, every run of characters that are not letters or digits (of any language) replaced by -, dashes trimmed from both ends. If nothing is left, the id is section.
A new id never repeats an id already used anywhere in the page or in root, including ids of later headings: it gets -2, -3… (the first free number). The id is set on the heading itself.
Running buildToc again on the same article gives the same entries and ids. Other elements' ids are never changed.
renderToc builds the nested lists described above; an entry without children has no nested <ul>, and no entries give an empty <ul>.
renderToc writes the text as text: a heading that contains < or & never turns into markup.