I was trying to find a simple way to add a table of content to an individual page in Ghost
The following code works perfectly for me.
Just paste the code directly into the actual page (using the ‘HTML’ element) below your title and above where your content will start.
I have it set to just add H2 items, but I’m sure it can be adjusted. You can also edit some of the display settings as you wish.
I haven’t tried it on ‘posts’ (as I already have that installed in the theme)
Hopefully this is useful to someone
<div id="toc-placeholder">
<script>
window.addEventListener('DOMContentLoaded', function () {
const tocContainer = document.createElement('div');
tocContainer.id = 'toc';
tocContainer.innerHTML = '<h2>Table of Contents</h2><ul>';
const h2Elements = document.querySelectorAll('h2');
h2Elements.forEach(h2 => {
const listItem = document.createElement('li');
const link = document.createElement('a');
link.href = '#' + h2.id; // Ensure "#" before the ID
link.textContent = h2.textContent;
listItem.appendChild(link);
tocContainer.querySelector('ul').appendChild(listItem);
});
const placeholder = document.getElementById('toc-placeholder');
placeholder.parentNode.replaceChild(tocContainer, placeholder);
});
</script>
<style>
#toc {
background-color: #f0f0f0;
padding: 20px;
border: 1px solid #ccc;
}
#toc ul {
list-style-type: none;
margin: 0;
padding: 0;
}
#toc a {
color: #333;
text-decoration: none;
}
</style>
</div>