Create smart table of contents with HTML and JavaScript

This script searches for h2 tags and then extracts links to these headings, the table of contents is generated before these headings
<div id="category-body">
<ul id="toc"></ul>
<h2 >heading 1</h2>
<h2 >heading 2</h2>
<h2 >heading 3</h2>
<h2>heading 4</h2>
</div>

The script must be placed after the headings that you want to appear in the table of contents

<script>
var ss=document.getElementById("category-body");
var ss2=document.getElementsByTagName("h2");
var i; var j;
if(ss2.length > 0){
document.getElementById("toc").innerHTML+='<p>Contents:</p><style>ul#toc {list-style: none;box-shadow: 0 0 2px 0;width: max-content;min-width: 130px;padding: 1px 1px 13px 8px;}ul#toc li { margin-left: 30px; list-style: decimal; }#toc li a { text-decoration: none; }<"+"/style>'

for (i = 0; i < ss2.length ; i++){
add_id=ss2[i].innerHTML;
var dd=ss2[i].innerHTML;
var dd2=ss2[i].id=add_id ;
document.getElementById("toc").innerHTML+="<li><a href='#"+dd2+"' >"+dd+"</a></li>"


}};

</script>
Create smart table of contents with HTML  and JavaScript,  table of contents, html javascript

© 2025 Manajmnt code

Share to :

Related

Comments

Post a Comment

message