How to build/compile/make a Table of Contents automatically based on a fixed HTML code?

109 views Asked by At

If I have a lot of articles which have various headings, how can I build/compile/make a flexible Table of Contents for all those articles automatically?

1

There are 1 answers

0
Louis55 On BEST ANSWER

First, you need jQuery and a fixed layout for all of your articles like this HTML:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<div class='post-content'>
<div class='table-of-contents'></div>
<div id='anchor-a'>Heading A</div>
<div id='anchor-b'>Heading B</div>
<div id='anchor-c'>Heading C</div>
<!-- and so on -->
</div>

Second, add a line of word - Table of Contents and an un unordered HTML list:

$('div.table-of-contents').html("<div>Table of Contents</div><ul></ul>");

Third, add a list of headings in the unordered HTML list:

  $('div.post-content div[id^=anchor-]').each(function(){
    $('div.table-of-contents ul').append("<li><a href='#" + $(this).attr('id') + "'>" + $(this).text() + "</a></li>");
  }

Finally, customize your Table of Contents with CSS.


Here is an working example:

$(document).ready(function(){
  $('div.table-of-contents').html("<div>Table of Contents</div><ul></ul>");
  $('div.post-content div[id^=anchor-]').each(function(){
    $('div.table-of-contents ul').append("<li><a href='#" + $(this).attr('id') + "'>" + $(this).text() + "</a></li>");
  });
});
div.table-of-contents {
  border: 2px solid black;
  display: inline-block;
}
div.table-of-contents div {
  font-size: x-large;
  font-weight: bold;
  padding: 5px;
  border-bottom: 1px solid black;
}
div.table-of-contents ul {
  padding: 5px 5px 5px 30px;
  margin: 0;
}
div.table-of-contents ul li {
  font-size: large;
}
div[id^="anchor-"] {
  margin-top: 1em;
  font-size: large;
  font-weight: bold;
}
div.footer {
  height: 2000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='post-content'>
<div class='table-of-contents'></div>
<hr/>
<div id='anchor-a'>Heading A</div>
content of anchor-a
<hr/>
<div id='anchor-b'>Heading B</div>
content of anchor-b
<hr/>
<div id='anchor-c'>Heading C</div>
content of anchor-c
<hr/>
</div>
<div class='footer'>footer</div>