Which javascript library or framework supports generating "Table Content"?

I'm looking for javascript "on the fly" generation "Content" from HTML (with anchors).

Example:

<h1>First level1 heading</h1>
lorem ipsum
<h2>1a heading</h2>
lorem ipsum
<h2>1b heading</h2>
lorem ipsum
<h1>Second level1 heading</h1>
lorem ipsum

      

Should return something like

 First level1 heading   
   1a heading   
   1b heading 
 Second level1 heading

      

with lines associated with headers, and an html orignal with anchors attached should also be returned.

Is there something in one of the big javascript libraries or frameworks?

If none of them have, has anyone seen a good JS module for this purpose?

0


a source to share


3 answers


jQuery is your friend with this plugin: table of contents . Home page http://code.google.com/p/samaxesjs/



+4


a source


DIY, I wrote this :) hope it helps

add a div element as the first child of the body and give the id as "tableOfContents"

and add the script below as the last child of the body



<script>
    var el = document.getElementsByTagName("*") || [];
    var toc = "<ul>";
    var lvl = 1;
    for(var i=0;i<el.length;i++)
    {
        var ce = el[i];
        var tag = ce.tagName + "";
        var m = tag.match(/^h([1-5])$/i);
        if(m)
        {
            var n = Number(m[1]);
            if(lvl > n)
            {
                while(lvl-->n)toc+="</ul></li>";  
            }else if(lvl < n){
                while(lvl++<n)toc+="<li style='list-style:none'><ul>";
            }
            toc +=  '<li><a href="#toc_' + i + '">' + 
                    (ce.innerText || ce.text()) +
                    '</a></li>';
            var ta = document.createElement("div");
            ta.innerHTML = '<a name="toc_' + i + '" />';
            ce.insertBefore(ta, ce.firstChild);
        }
    }
    while(lvl-->1)toc+="</ul></li>";
    toc+="</ul>";
    document.getElementById("tableOfContents").
        innerHTML = toc;
</script>

      

this script will define every H (1 to 5) and generate your table of contents

+1


a source


This is a very simple problem that can be solved with a 10-20 line function. No framework required. Either traverse the DOM with getElementsByTagName ('h1'), getElementsByTagName ('h2'), or use regular expressions. Downloading frameworks comes with implications and risks to work with, so I suggest not installing them for simple problems.

-1


a source







All Articles