SiteExperts.com Logo Home | Community | Developer's Paradise | Jobs
User Groups | Site Tools | Site Information | Search

Inside Technique : Part II - W3C DOM Table of Contents : Enhancing the Code

In our original script, the getHeaders() function did the bulk of the work. This function enumerates all the headers in the document and builds the table of contents as a nested list:


function getHeaders() {
 var obj = document.getElementsByTagName("*")
 var el = document.createElement("UL")
 var tagList = "H1;H2;H3;H4;H5;H6;"
 for (var i=0;i < obj.length;i++)
  if (tagList.indexOf(obj[i].tagName+";")>=0) {
   // Create the LI element
   var eLI = document.createElement("LI")
   eLI.className="toc" + obj[i].tagName

   // Insert the header text
   var eLIText = document.createTextNode(getTextForElement(obj[i]))

   // Build the tree  
   eLI.appendChild(eLIText)
   el.appendChild(eLI)
  }
 return el
}

We built the table of contents element by element. First we constructed the UL container element and then for each header in the document we inserted an LI element - within each LI element is a text node containing the actual header text. When we are finished with this function, we have a simple HTML fragment containing the complete table of contents.

To make the table of contents live, we enhance our construction code to insert a link around each list item. We also insert a destination for the link in the document. Our new getHeaders() function is as follows:

function getHeaders() {
 var obj = document.getElementsByTagName("*")
 var el = document.createElement("UL")
 var tagList = "H1;H2;H3;H4;H5;H6;"
 for (var i=0;i < obj.length;i++)
  if (tagList.indexOf(obj[i].tagName+";")>=0) {
   // Create the LI element
   var eLI = document.createElement("LI")
   eLI.className="toc" + obj[i].tagName
   // Create the bookmark
   var eBookmark = document.createElement("A")
   // Set the destination ID
   eBookmark.id  = "destHeader" +i
   // Create the link
   var eALink = document.createElement("A")
   eALink.href = "#" + eBookmark.id

   // Build the tree
   var eLIText = document.createTextNode(getTextForElement(obj[i]))
   obj[i].appendChild(eBookmark)
   eALink.appendChild(eLIText)  
   eLI.appendChild(eALink)
   el.appendChild(eLI)
  }
 return el
}

That's all there is to making the table of contents live. Next, we explain how this function builds the table of contents.