Using JavaScript to generate table of contents for a webpage

Combing the DOM (Document Object Model) with JavaScript makes it easy to dynamically build the TOC. Now I only have to add extra sections and they are automatically added to the TOC. Clicking the item in the TOC will go to the section on the page.

An easy solution. Nice.

Code

[<ul id="toc"></ul>

function buildTOC() {
   // get bullet list holder
   var toc = document.getElementById("toc");

   // get all anchors on the page
   var anchors = document.anchors;
   for (var i=0; i]
[<a name="section1" class="no_style">]Section 1[</a>]
Ut dolore veniam ullamcorper iriure molestie in commodo aliquip sed in enim accumsan iriure iusto. Dolore dolore eu tation ut hendrerit tincidunt vulputate nulla. Exerci, vulputate velit, quis dignissim minim, blandit nonummy facilisis at blandit augue nostrud magna nonummy, wisi nulla consequat. Enim odio, in nostrud zzril ut consequat accumsan delenit feugait suscipit volutpat ut et at. Augue nisl praesent molestie qui ut dolore eum minim vel dolor luptatum vero magna iusto et.

[<a name="section2" class="no_style">]Section 2[</a>]
Consequat exerci feugiat eum augue accumsan feugiat blandit odio. Tation te, vel dolore duis te commodo elit qui at in feugait iriure vero, ullamcorper nostrud lorem ipsum feugiat, erat ex. Eros vel nonummy zzril wisi quis consequat in autem ut suscipit amet, amet erat at duis minim in molestie.

[<a name="section3" class="no_style">]Section 3[</a>]
Eu esse at et feugait elit, lorem, zzril, blandit eum facilisi feugiat, commodo nulla ut vel tation euismod accumsan, qui. Duis, in amet vel esse ad, ad vero vel facilisis minim in nisl laoreet iriure tation eros molestie dolor. Odio vel quis nostrud autem dolor et exerci vulputate augue erat in nisl iusto dolore vulputate, aliquam, laoreet ullamcorper dignissim dolor adipiscing ad qui. Hendrerit te at diam ea quis, aliquip molestie wisi erat praesent, luptatum adipiscing nonummy nostrud zzril nisl consequat et euismod. Enim ullamcorper consequat lobortis, minim wisi augue nisl diam, esse suscipit duis ex eum odio dolore, ut ut. Delenit ex iusto et ex, ex tincidunt illum luptatum eu te in in feugiat minim augue, sit dolore blandit iusto, consequat duis vel nulla duis at.

Result

Published by

lekkim

Positive, competent, out-spoken, frank and customer focused architect and developer with a strong foundation in web, cloud and product development. I'm a strong advocate for API first and cloud based solutions and development. I have a knack for being able to communicate and present technically complicated matters in conference, customer and training settings. I've previously acted as team member and leader in a product organisation.