• الصفحة الرئيسية
  • إتصل بنا
  • سياسة الخصوصية
Logo
  • الرئيسية
  • أفكار
  • صحة
  • معلومات
  • عجائب وغرائب
  • تكنولوجيا
الصفحة الرئيسية JavaScript Programming Guide How to Create Table of Contents Using JavaScript

How to Create Table of Contents Using JavaScript

الكاتب ahmed في 10:08 PM JavaScript Programming Guide

You can create dynamic table of contents for any HTML document using JavaScript which can show the list of headings from h1 to h6 with links to the headings and make easier to navigate through the document.

In this post I am going to describe about the steps to Create Table of Contents Using JavaScript and about the JavaScript codes required to create dynamic table of contents.

To create this set of JavaScript codes for creating table of contents, at first you have to know the different JavaScript concepts like selecting elements, document traversal, setting element attributes, setting innerHTML property, creating nodes and inserting then into the document.


Steps to Create Table of Contents Using JavaScript


At first create window.onload function that runs automatically when the document finishes loading as given below.

window.onload=function(){

function getSelectedText(){
if (window.getSelection)
return window.getSelection().toString()+"
"+document.URL;
else if (document.selection)
return document.selection.createRange().text+"
"+document.URL;
}
var toc=document.getElementById("TOC");
if(!toc) {
toc=document.createElement("div");
toc.id="TOC";
document.body.insertBefore(toc, document.body.firstChild);
}

When the above function runs, it first looks for a document element with an id of "TOC". If there is no such element it creates on at the start of the document.

Add the following codes to the function to find all <h1> through <h6> tags and sets them as headings.

var headings;
if (document.querySelectorAll)
headings=document.querySelectorAll("h1, h2, h3, h4, h5, h6");
else
headings=findHeadings(document.body, []);

Then recursively traverse the document body looking for headings using function: findHeadings(root, sects){  }

Initialize an array: var sectionNumber=[0,0,0,0,0,0]; that keeps track of section numbers and add section numbers to each section numbers to each section heading and wrap the headings in named anchors so that the TOC can link to them.

Write CSS code to style created table of contents. Where all entries have a class "TOCEntry" and the section headings from <h1> to <h6> have class name "TOCLevel1" to "TOCLevel6" and the section number inserted into headings have class "TOCSectNum".

Full CSS Code To Style Table of Contents


 Here is a full CSS code within <style> </style> tag to style table of contents.

<style>
#TOC {border:solid black 1px; margin:10px; padding:10px;}
.TOCEntry{font-family:sans-serief;}
.TOCEntry a{text-decoration:none;}
.TOCLevel1{font-size:17pt; font-weight:bold;}
.TOCLevel2{font-size:16pt; font-weight:bold;}
.TOCLevel3{font-size:15pt; font-weight:bold;}
.TOCLevel4{font-size:14pt; margin-left:.25in;}
.TOCSectNum{display:none;}
</style>

Full JavaScript Code To Create Table of Contents



Here is a full JavaScript Code To Create Table of Contents within <script> </script> tag.

<script>
window.onload=function(){

function getSelectedText(){
if (window.getSelection)
return window.getSelection().toString()+"<br/>"+document.URL;
else if (document.selection)
return document.selection.createRange().text+"<br/>"+document.URL;
}

var toc=document.getElementById("TOC");
if(!toc) {
toc=document.createElement("div");
toc.id="TOC";
document.body.insertBefore(toc, document.body.firstChild);
}
var headings;
if (document.querySelectorAll)
headings=document.querySelectorAll("h1, h2, h3, h4, h5, h6");
else
headings=findHeadings(document.body, []);

function findHeadings(root, sects){
for(var c=root.firstChild; c!=null; c=c.nextSibling){
if (c.nodeType!==1) continue;
if (c.tagName.length==2 && c.tagName.charAt(0)=="H")
sects.push(c);
else
findHeadings(c, sects);
}
return sects;
}

var sectionNumbers=[0,0,0,0,0,0];

for(var h=0; h<headings.length; h++) {
var heading=headings[h];

if(heading.parentNode==toc) continue;

var level=parseInt(heading.tagName.charAt(1));
if (isNaN(level)||level<1||level>6) continue;

sectionNumbers[level-1]++;
for(var i=level; i<6; i++) sectionNumbers[i]=0;

var sectionNumber=sectionNumbers.slice(0, level).join(".");

var span=document.createElement("span");
span.className="TOCSectNum";
span.innerHTML=sectionNumber;
heading.insertBefore(span, heading.firstChild);
heading.id="TOC"+sectionNumber;
var anchor=document.createElement("a");
heading.parentNode.insertBefore(anchor, heading);
anchor.appendChild(heading);

var link=document.createElement("a");
link.href="#TOC"+sectionNumber;
link.innerHTML=heading.innerHTML;

var entry=document.createElement("div");
entry.className="TOCEntry TOCLevel" + level;
entry.appendChild(link);

toc.appendChild(entry);
}
};

</script>

You can see the preview of Table of contents generated by JavaScript code above. If you have any problem or difficulties while implementing the above JavaScript code, you are welcomed to mention on the comment session at the bottom this post.



Related Search Terms

  • TOC for HTML Document Using JavaScript

  • Create Table of Contents Using JavaScript

     

Related Posts:

  • How to Show Pop Up Window Using JavaScript

  • How to go Back Browsing History Using JavaScript

  • How to Click Button Using JavaScript?

  • How to Write JavaScript Function as URL in Hyperlink?

  • How to use Round, Random, Min and Max in JavaScript

  • How to Concatenate, Join and Sort Array in JavaScript?

  • How to Loop Through JavaScript Array?

  • How to Loop using JavaScript?

  • How to Show Pop Up Boxes Using JavaScript?

  • How to Write Conditional Statements in JavaScript?

  • How to Write JavaScript With HTML?

  • How to create Changeable Date and Time Using JavaScript?

  • How to Validate a HTML Form Using JavaScript?

  • How to create a simple form using HTML?

  • How to Create JavaScript Image Sideshow with Links

  • How to Display Date Format in JavaScript?

  • How to Validate a HTML Form Using JavaScript?

  • What are the Different Ways to Redirect Page in JavaScript?

  • How to create Timer Using JavaScript?

  • How to make rounded corners border using CSS

  • How to Create Custom CSS Template for Printing

  • How to create a simple form using HTML?

شارك المقال :
Tweet
✚

مقالات ذات صلة

التالي
المشاركةالتالية
السابق
المشاركة السابقة

تحويل كودإخفاء محول الأكواد الإبتساماتإخفاء

شكرا لمشاركتنا رأيك
Subscribe to: Post Comments (Atom)
  • Facebook
  • twitter
  • googleplus
  • youtube
  • linkedin

الأكثر زيارة

  • What is Information ?
    Information  can be defined as data that has been processed into a form that is meaningful to the recipient and is of real or perceived valu...
  • What is Information Technology?
    Definitions of  Information technology  ( IT ) It is a branch of engineering dealing with the use of computers and telecommunications equipm...
  • بالصور الفائزة بمسابقة ملكة جمال مصر 2017
    بالصور الفائزة بمسابقة ملكة جمال مصر 2017
    بالصور الفائزة بمسابقة ملكة جمال مصر 2017 لن تصدق من هي فرح صدقي ↓↓  لمشاهدة الصور والخبر كامل اضغط هنا  ↓↓ رابط المو...
  • Interview Questions on Stack and Queue in Data Structure set-2
    1) The queue in which the insertion takes place in the first position after of last element is a ...... A. priority B. dequeue C. circular D...
  • List of Top 65 Search Engine Submission Add URLs.
    List of Top 65 Search Engine Submission Add URLs.
    To get your site on the top ranking on the search engine results, Your site or URL must be indexed by Search Engines. For that you have to s...
  • List of Best Keyword Research Tools for Better SEO
    List of Best Keyword Research Tools for Better SEO
    Everyone needs to do keyword research work for the site before starting search engine optimization work as the first and most essential tas...
  • What are the different types of scheduling methods?
    Process scheduling is one way for a processor to handle n processes , by scheduling the execution process. Each process is executed one by ...
  • Solved MCQ on Database Backup and Recovery in DBMS set-1
    1) Which of the following is not a recovery technique? A. Deferred update B. Immediate update C. Two-phase commit D. Recovery management 2)C...
  • Solved MCQ on Distributed Database Transaction Management set-4
    1) Commit and rollback are related to .......... A. data integrity B. data consistency C. data sharing D. data security 2) The transaction w...
  • Solved MCQ on Fundamental of DBMS set-10
    1) Which of the following is not a characteristic of a relational database model? A. Table B. Tree like structure C. Complex logical relatio...

الأقسام

  • Artificial Intelligence(AI)
  • Backlinking
  • Basic IT
  • Best List
  • Blogging Tips
  • C
  • C#
  • C++
  • Computer Architecture
  • Computer Fundamental
  • Computer Security
  • Computer/IT Officer Exam
  • CSS
  • Data Mining and Warehousing
  • Data Recovery Tools
  • Data Structure
  • Database Management System
  • E-commerce
  • E-government
  • Internet & Web Designing
  • IT Law
  • IT Tips and Tricks
  • IT Tutorials
  • Java
  • JavaScript
  • Keyword Research Tools
  • MIS
  • Multiple Choice Question (MCQ)
  • Networking
  • Online Earning
  • Online IT Jobs
  • Operating System
  • Oracle Forms and Reports
  • Programming Guide
  • Programming Language
  • SEO
  • Social Networking Sites
  • Software Download
  • Software Engineering
  • System Analysis and Design
  • Top List
  • VB.Net
  • صحة
  • عجائب وغرائب

الأرشيف

  • ►  2017 (4)
    • ►  November (3)
    • ►  October (1)
  • ►  2016 (5)
    • ►  April (5)
  • ▼  2015 (87)
    • ►  August (1)
    • ►  July (8)
    • ►  June (13)
    • ►  May (2)
    • ►  April (2)
    • ►  March (4)
    • ▼  February (20)
      • How to Scroll Top or Bottom of Document Using Java...
      • How to Create Table of Contents Using JavaScript
      • How to Select Document Elements Using JavaScript?
      • How to Show Pop Up Window Using JavaScript
      • How to go Back Browsing History Using JavaScript
      • How to Click Button Using JavaScript?
      • How to Create JavaScript Bookmarklet?
      • How to Write JavaScript Function as URL in Hyperlink?
      • How to create Timer Using JavaScript?
      • How to create a Simple calculator Using HTML and J...
      • How to use Round, Random, Min and Max in JavaSript
      • How to Concatenate, Join and Sort Array in JavaScr...
      • How to Loop Through JavaScript Array?
      • How to Loop using JavaScript?
      • How to Show Pop Up Boxes Using JavaScript?
      • How to Write Conditional Statements in JavaScript?
      • How to Write JavaScript With HTML?
      • How to create Changeable Date and Time Using JavaS...
      • How to Validate a HTML Form Using JavaScript?
      • How to create a simple form using HTML?
    • ►  January (37)
  • ►  2014 (77)
    • ►  December (31)
    • ►  November (4)
    • ►  September (4)
    • ►  August (11)
    • ►  July (8)
    • ►  June (2)
    • ►  May (2)
    • ►  April (2)
    • ►  March (2)
    • ►  February (7)
    • ►  January (4)
  • ►  2013 (132)
    • ►  December (11)
    • ►  November (6)
    • ►  October (4)
    • ►  September (6)
    • ►  August (16)
    • ►  July (9)
    • ►  June (9)
    • ►  May (12)
    • ►  April (13)
    • ►  March (23)
    • ►  February (6)
    • ►  January (17)
  • ►  2012 (59)
    • ►  December (15)
    • ►  November (20)
    • ►  October (21)
    • ►  September (3)

إنضم لنا

© 2017 أفكار جميع الحقوق محفوظة