JSFiddle - React, Tailwind, and code Playground

by meGAmeS1

HTML

<div id="content">
    <div id="test">
        <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>
</div>
<div style="color: green;">
    <h3 class="show-in-toc">Result</h3>
    <pre id="result">
    </pre>
</div>

JavaScript

function headerTagToObject(tag, level) {
    tag = $(tag);
    return {
        'title': tag.text(),
        'level': level,
        'children': []
    }
}

function generateToc(level, filter = undefined, initial_parent = undefined, parent = undefined) {
    var result, tags;
    result = [];
    if (parent) {
        tags = $(parent).nextUntil('h' + (level - 1), 'h' + level).filter(filter);
        // tags = $(parent).nextUntil('h' + (level - 1)).find('h' + level).filter(filter);
    } else {
        if (initial_parent) {
            tags = $(initial_parent).find('h' + level).filter(filter);
        } else {
            tags = $('h' + level).filter(filter);
        }

    }

    tags.each(function(i, tag) {
        var tagResult;
        tagResult = headerTagToObject(tag, level);
        tagResult['children'] = generateToc(level + 1, filter, initial_parent, tag);
        result.push(tagResult);
    });
    return result;
}
//headings = $('.show-in-toc:header').toArray();
//debugger;
result = generateToc(2, '.show-in-toc', '#content');
//console.log(result);
$('pre#result').html(JSON.stringify(result, null, '  '));