// makes a table of contents // top level is h2, goes down from there let elt_toc = document.getElementById("toc"); let elts_enum = document.getElementsByClassName("enum"); // top level is h2 // if we see a bigger level let last_level = 2; let h2_idx = 0; let h3_idx = 0; let h4_idx = 0; let h5_idx = 0; // if we see an h2, reset the h3/h4/h5 indexes to 0 // if we see an h3, reset the h4/h5 indexes to 0 // so on function reset_below(level) { switch(level) { case 2: h3_idx = 0; case 3: h4_idx = 0; case 4: h5_idx = 0; default: break; } } // str index; e.g. "1.3.4" function str_idx(level) { // build up components in reverse // so an h4 shouldn't have any h5 data let components = []; switch(level) { case 5: components.push(h5_idx); case 4: components.push(h4_idx); case 3: components.push(h3_idx); case 2: components.push(h2_idx); default: break; } components.reverse(); return components.join("."); } // when we see a new element, increment the index function incr(level) { switch(level) { case 2: h2_idx += 1; break; case 3: h3_idx += 1; break; case 4: h4_idx += 1; break; case 5: h5_idx += 1; break; default: break; } } for (let this_enum_elt of elts_enum) { switch(this_enum_elt.tagName) { case "H2": this_level = 2; break; case "H3": this_level = 3; break; case "H4": this_level = 4; break; case "H5": this_level = 5; break; default: this_level = 0; } //console.log(this_enum_elt); // increment index, reset those below // so if we see an h2, bump up the h2 index, reset h3/h4/h5 to 0 reset_below(this_level); incr(this_level); // "Foo Bar" -> "1.3.4. Foo Bar" let old_section_title = this_enum_elt.innerText; let new_section_title = str_idx(this_level) + ". " + this_enum_elt.innerText; this_enum_elt.innerText = new_section_title; //console.log(new_section_title); let entry_a = document.createElement('a'); // make an id for this entry if it doesn't exist if (!this_enum_elt.id) { // "Foo Bar" -> "foo-bar" let words = old_section_title.split(" "); let ident = words.map(function (s) { return s.toLowerCase(); }).join("-"); this_enum_elt.id = ident; } entry_a.href = "#" + this_enum_elt.id; entry_a.innerText = new_section_title; entry_a.classList += "toc" + this_level; //console.log(entry_a); let entry_br = document.createElement('br'); toc.appendChild(entry_a); toc.appendChild(entry_br); }