JSFiddle - React, Tailwind, and code Playground
HTML
<div>
<h2>heading 1</h2>
<h3>header 1 1</h3>
<h3>header 1 2</h3>
<h3>header 1 3</h3>
<h2>heading 2</h2>
<h2>heading 3</h2>
<h3>header 3 1</h3>
<h3>header 3 2</h3>
<h3>header 3 3</h3>
<h2>heading 4</h2>
<h2>heading 5</h2>
<h3>header 5 1</h3>
<h3>header 5 2</h3>
<h3>header 5 3</h3>
<h2>heading 6</h2>
</div>
JavaScript
$('document').ready(function(){
$('h2:first').parent("div").addClass("multiplecontent");
var toTop = '<span class="top">Back to top</span>';
var openLinks = '<div class="indexholder"><h2>On this page</h2><ul class="index">';
var closeLinks = '</ul></div>';
$('.multiplecontent').before(openLinks);
$('.multiplecontent h2').each(function(i){
console.log('has h2');
var i = [i+1];
var nTitle = $(this).html();
var nItems = 'item' + i;
var nIndex = 'index' + i;
var nItem = '<li id=' + nIndex + '>' + nTitle + '</li>';
$('ul.index').append(nItem);
$(this).attr('id', nItems);
$(this).siblings('h3').each(function(i)
{
console.log('has h3');
var nItemChild = '';
var nItemsChild = 'itemChild' + i;
var nIndexChild = 'indexChild' + i;
var nTitleChild = $(this).html();
nItemChild = '<li><ul><li id=' + nIndexChild + '>' + nTitleChild + '</li></ul></li>';
$('ul.index').append(nItemChild);
$(this).attr('id', nItemsChild);
});
$('#' + nIndex).click(function (){
$('html, body').animate({
scrollTop: $('#' + nItems).offset().top
}, 1000);
});
});
$('.multiplecontent h2').not(":first-child").before(toTop);
$('.multiplecontent h2 h3').not(":first-child").before(toTop);
$('.multiplecontent').append(toTop);
//$('.multiplecontent p:last').after(toTop);
$('.multiplecontent h2').not(":first-child").addClass("liner");
$('.multiplecontent').before(closeLinks);
$('span.top').click(function (){
$('html, body').animate({
scrollTop: $('#header').offset().top
}, 1000);
});
});