I have a chunk of JavaScript code that I use to dynamically create a table of contents for the page that it's on. It builds the table of contents as a string in a variable, then adds it to a specified block using the innerHTML property.
I'd rather do this with the JavaScript DOM: createElement & appendChild, etc. I just can't seem to get my head around how to accomplish this.
Can anyone offer a suggestion?
Here's the code:
Thank you.
--
-- Ghodmode
Give a man a fish and he'll come back to buy more... Teach a man to fish and you're out of business.
I'd rather do this with the JavaScript DOM: createElement & appendChild, etc. I just can't seem to get my head around how to accomplish this.
Can anyone offer a suggestion?
Here's the code:
Code:
function pageContents( contents_block_id ) {
var content_block = document.getElementById( "content" );
var elements = content_block.getElementsByTagName( "*" );
var contents = document.getElementById( contents_block_id );
var contents_list = new Array;
var previous_level = 1;
var depth = 1;
var doclinks = new Array();
var html = "<ul>\n";
html += "<li><a href='#Top' class='toplink'>top</a></li>\n";
for ( i = 0; i < elements.length; i++ ) {
if ( ! elements[i].tagName.match(/^H\d/) ) { continue; }
var level = elements[i].tagName.substr(1, 1);
var text = elements[i].innerHTML;
var link = text.replace( /\W/g, "" );
doclinks.push( [elements[i], link] );
if ( level > previous_level ) {
html += "<li>\n <ul>\n";
depth++;
}
if ( level < previous_level ) {
html += " </ul>\n</li>\n";
depth--;
}
html += " <li><a href='#" + link + "'>" + text + "</a></li>\n";
previous_level = level;
}
for ( i = depth; i > 1; i-- ) {
html += "</ul>\n</li>\n";
}
html += "</ul>";
contents.innerHTML += html;
for ( i = 0; i < doclinks.length; i++ ) {
var element = doclinks[i][0];
var link = doclinks[i][1];
var a = document.createElement( "A" );
a.name = link;
content_block.insertBefore( a, element );
}
} // End pageContents function
Thank you.
--
-- Ghodmode
Give a man a fish and he'll come back to buy more... Teach a man to fish and you're out of business.