Javascript - Building a dynamic Table of Contents in Sharepoint using pure JS

164 Views Asked by At

Lets say you have a giant sharepoint wiki page with several heading tags (e.g. H1,H2,H3,H4) and you want to build a dynamic ToC using said tags.

I want to group these tags by group and use the html <detail> tag to display/hide the sub-heading. So something like this.

<details>
  <summary> H1 GOES HERE </summary>
    <li> H2 GOES HERE </li>
    <li> H3 GOES HERE </li>
    <li> H4 GOES HERE </li>
</details>

Here's the javascript that I currently have, but I cant seem to group them correctly after every tag so that the </details> tag get placed under each group.

function nodesToc() {
            /* Get all HTML tags from the current page */
            var obj1 = document.querySelectorAll("h1");
        var obj2 = document.querySelectorAll("h2,h3,h4");
            var str = "";
            
            /* Loop on each HTML tag */
            /* Get the  H1 tags to build the parent title */
            for (var i = 0; i < obj1.length; i++) {
              str += "<details><summary class='" + getClassLvl(obj1[i].tagName) + "'><a href='#title-" + i + "'> " + obj1[i].innerHTML + "</a></summary>";
               /* Get subsequent tags to build the sub-headings */
              for (var j = 0; j < obj2.length; j++) {       
                 str += "<li class='" + getClassLvl(obj2[j].tagName) + "'><a href='#title-" + j + "'> " + obj2[j].innerHTML + "</a></li>";
        }
                
        str += "</details>";                
        obj1[i].id = "title-" + i;
        }   

        return str;
}

Any help with this logic is appreciated. Note: I've tried several other JS solutions but Sharepoint seems to behave very buggy. Using the tag seems to be the cleanest solution to this problem.

As you can see from the code above, I tried a nested loop thinking I could capture the sub-headings, but I cant seem to group them correctly.

1

There are 1 best solutions below

0
Magnus On

Another solution is to use a webpart that generate a ToC: https://github.com/RedEchidnaUK/Table-of-Contents/tree/master

I´m using it, and it also have the option to "sticky" the ToC.