SharePoint Wiki Automatic Table Of Contents using JavaScript

ShadowIT used Ask the Experts™
Hello Experts,

I am attempting to have a table of contents generate automatically on SharePoint Online's Enterprise Wiki.  I came across this article that is exactly on point for this topic; however, upon initial implementation it didn't work as expected.

Further investigation led me to realize the classes defined within the code weren't correct so I update them and now the TOC does automatically generate based upon the heading type; however, there's no level differentiation in terms of the TOC's outline occurring so H1 is at the same outline level as say  H4.  

Unfortunately I am not well-versed in java script so I was wondering if one of you could lend me a hand?

Thank you

Incorrect Style Outline

#toc {

 display: table;

 border: 1px solid #aaa;

 background-color: #f9f9f9;

 font-size: 95%;

 padding: 7px;


#toc #tocHeader  {

 font-weight: bold;

 text-align: center;


#toc a:before { /* content:"• "; */ }

#toc a { line-height: 15px; margin: 10px; }

#toc .toc_Level1 { margin-left: 5px; }

#toc .toc_Level2 { margin-left: 15px; }

#toc .toc_Level3 { margin-left: 25px; }

#toc .toc_Level4 { margin-left: 35px; }


<div id="toc"></div>

<script src=""></script>

<script type="text/javascript">

function GenerateTOC() {

  $("#toc").append('<p id="tocHeader">Contents</p>');

  $(".ms-rtestate-field h1,, .ms-rtestate-field h2,, .ms-rtestate-field h3,, .ms-rtestate-field h4,").each(function(i) {

 var currentNode = $(this);

  currentNode.attr("id", "title" + i);

 var linkClass = (currentNode.hasClass('.ms-rtestate-field h1') || currentNode.hasClass(''))

   ? "toc_Level1"

   : (currentNode.hasClass('.ms-rtestate-field h2') || currentNode.hasClass(''))

   ? "toc_Level2"

   : (currentNode.hasClass('.ms-rtestate-field h3') || currentNode.hasClass(''))

   ? "toc_Level3"

   : (currentNode.hasClass('.ms-rtestate-field h4') || currentNode.hasClass(''))

   ? "toc_Level4"

   : "";

  $("#toc").append("<a id='link'" + i + "' class='" + linkClass + "' href='#title" + i + "' title='" + currentNode.attr("tagName") + "'>" + currentNode.html() + "</a><br>");

  currentNode.append(" <a href='#tocHeader'>[top]</a>");





Open in new window

Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
kukdaiSharePoint SME

Have you tried adding !important in the CSS for each level class.
Do an F12 and investigate the css, for each element where you can see if the margin is taking effect or not.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial