JSFiddle - React, Tailwind, and code Playground
by flyingsheep
HTML
<section id="toc" title="Table of Contents"></section>
<section>
<h1>Eins</h1>
Erstes Kapitel
<section>
<h1>Eins.Eins</h1>
Erstes Unterkapitel
</section>
<section>
<hgroup>
<h1>Eins.Zwei</h1>
<h2>Mit Untertitel!</h2>
</hgroup>
Zeites Unterkapitel
</section>
</section>
<section>
<h1>Zwei</h1>
Zweites Kapitel
</section>
CSS
#toc:before {
padding-right: 15px;
padding-left: 15px;
font-size: 150%;
}
#toc h1, #toc h2, #toc h3, #toc h4 {
margin: 0;
padding: 0;
font-size: 14px;
}
#toc h2 {
padding-left: 1em;
}
#toc h3 {
padding-left: 2em;
}
#toc h4 {
padding-left: 3em;
}
JavaScript
var toc = $("#toc");
var h1c = $("article,section").not("footer section").find("h1").size();
var hcnt = {};
if (toc.attr("title") !== "") {
$("head").append("<style type='text/css'>#toc:before { content: '" + toc.attr("title") + "'; }</style>");
}
if (toc.size()) {
$("article,section").not("footer section").find("h1, h2, h3, h4").each(function(i, e) {
var build_chapnum = function(u, v, w) {
v += hcnt[w] + ".";
if (w == u) {
return v;
} else {
return build_chapnum(u, v, w + 1);
}
}
var clear = function(u) {
if (u < 7) {
u++;
hcnt[u] = undefined;
clear(u);
}
return;
}
var t = $(this);
var h = "";
var u = e.tagName.match(/\d+$/)[0];
if (hcnt[u] === undefined) {
hcnt[u] = 1;
} else {
hcnt[u]++;
}
t.text(build_chapnum(u, "", 1) + " " + t.text());
t.attr("id", t.text().replace(/[!\"#$%&'\(\)\*\+,\.;<=>\?\@\[\\\]\^`\{\|\}~äöüßÄÖÜ]/g, "").replace(/[ :/]/g, "_"));
if (e.tagName.toLowerCase() != "h1" || h1c != 1) {
h = t.attr("id");
}
toc.append("<" + e.tagName + "><a href='#" + h + "'>" + t.text() + "</" + e.tagName + ">");
clear(u);
});
}