Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<body>
<p id="tableOfContents"></p>
<h2>Chapter</h2> <br><br><br>
  <h3>Section</h3> <br><br><br>
  <h3>Section</h3> <br><br><br>
<h2>Chapter</h2> <br><br><br>
  <h3>Section</h3> <br><br><br>
  <h3>Section</h3> <br><br><br>
<script>
var allTitles = document.querySelectorAll("H2, H3");
var numberOfTitles = allTitles.length;
var toc = "";
for(t=0, c=0, s=0; t < numberOfTitles; t++)
{ 
  if(allTitles[t].nodeName == "H2")
  { 
    c++;
    allTitles[t].setAttribute("id", "chapter" + c);
    s=0;
    toc += "<a href=#chapter" + c + ">";
    toc += c + ". " + allTitles[t].innerHTML;
    toc += "</a>";
    toc += "<br>";
  }
  
  if(allTitles[t].nodeName == "H3")
  {
    s++;
    allTitles[t].setAttribute("id", "section" + c + "." + s);
    toc += "&nbsp;&nbsp;&nbsp;&nbsp;<a href=#section" + c + "." + s + ">";
    toc += c + "." + s + ". " + allTitles[t].innerHTML;
    toc += "</a>";
    toc += "<br>";
  }
}
document.getElementById("tableOfContents").innerHTML = toc;
</script>
</body>
</html>
Output

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
anonymouspro
0viewers