I'm trying to parse a list of headings (h1
, h2
, etc.) to obtain the table of content in a well structured javascript variable (kinda like a tree).
Here's the structure of my document:
<div id="content">
<h1>The content</h1>blah
<h2 class="show-in-toc">Test 1</h2>
<h3 class="show-in-toc">Test 1.1</h3>
<h3 class="show-in-toc">Test 1.2</h3>
<h4 class="show-in-toc">Test 1.2.1</h4>
<h4 class="show-in-toc">Test 1.2.2</h4>
<h2 class="show-in-toc">Test 2</h2>
<h3 class="show-in-toc">Test 2.1</h3>
<h4 class="show-in-toc">Test 2.1.1</h4>
<h3 class="show-in-toc">Test 2.2</h3>
</div>
And here's what I'm trying to get:
[
{"text": "Test 1","level": 2, "children": [
{"text": "Test 1.1","level": 3,"children": []},
{"text": "Test 1.2", "level": 3, "children": [
{"text": "Test 1.2.1", "level": 4, "children": []},
{"text": "Test 1.2.2", "level": 4, "children": []}
]}
]},
{"text": "Test 2", "level": 2, "children": [
{"text": "Test 2.1", "level": 3, "children": [
{"text": "Test 2.1.1", "level": 4, "children": []}
]},
{"text": "Test 2.2", "level": 3, "children": []}
]}
]
I'm guessing the function should be recursive and would look like this:
headings = $('.show-in-toc:header'); // Maybe .toArray() ?
toc = generateToc(headings, 2); // With 2 being the starting level
I tried to inspire an algorithm from this subject but I didn't get any result (they're directly putting the result into a dom element).
Have you any suggestion to guide me? Thank you in advance