How to Create an Automated Index of an HTML Document Step by Step
I'm going to show you how you can create a table of contents for your HTML document, a way to navigate between each of the content sections.
In this case, I configured the table of contents to take into account the elements from <h1> to <h3>, meaning those heading levels can be used as navigation links within the document.
function generateIndex() {
const indexContainer = document.createElement("div"); // Contenedor del índice
indexContainer.innerHTML = "<h2>Índice</h2>";
const list = document.createElement("ul");
// Obtener todos los encabezados h1, h2, h3 en el orden en que aparecen
const headers = document.querySelectorAll('.book-chapter h1, .book-chapter h2, .book-chapter h3');
let chapterToken = 'chapter1.xhtml'
headers.forEach((header, index) => {
// Generar un ID único si no tiene
// Crear el enlace al encabezado
const listItem = document.createElement("li");
const link = document.createElement("a");
link.href = "#" + header.id;
link.textContent = header.textContent;
// Agregar clase según el tipo de encabezado (para estilos)
if (header.tagName === "H1") listItem.classList.add("index-h1");
if (header.tagName === "H2") listItem.classList.add("index-h2");
if (header.tagName === "H3") listItem.classList.add("index-h3");
listItem.appendChild(link);
list.appendChild(listItem);
document.querySelector('#indexSection').appendChild(list);
});
}
In another post, I explained how to export and import HTML content using Google Docs.
It's important to note that each of these HTML elements must have a unique ID, as navigation from the table of contents works through links that point to those IDs.
In other words, the table of contents simply creates internal links of the type href="#my-id." Therefore, if the heading doesn't have a defined ID, navigation to that link won't be possible.
link.href = "#" + header.id;
We set the link variable to the text, which in this case would be the text of the <h1>, <h2>, or <h3>—again, using textContent.
And then the id, which will be used as the link's destination.
Here we also add some CSS classes. They aren't strictly necessary, but if you ever need them, you can add them there.
In this case, I did add them to add some classes for the tabs:
.index-h1 {
margin-left: 0px;
margin-top: 30px;
font-weight: bold;
}
.index-h2 {
margin-left: 30px;
}
.index-h3 {
margin-left: 60px;
}
Next, we add it to the <li> with li.appendChild(link), and we do the same with the <ul>: we add it somewhere in the document, which in this case is a div container with the class .index-section (that's what I called it). We insert it there, and it's working automatically.
I agree to receive announcements of interest about this Blog.
I explain how you can generate an index of an HTML document or Google Doc web page or a document in general.
- Andrés Cruz