Add scrollspy on document with only heading

59 views Asked by At

I have to add a scrollspy feature on a document which does not have <div> or <section> but only <h#> with id attribute. I can't modify the raw document structure. But I can modify it dynamically with JQuery. So I would like to generate div with the id attribute of my <h#> tag and wrap <h#> and all element until next same level <h#>.

I know that exist nextUntil() method and I try this (for test, it's not what I need) :

$("h1").each(function()
{
    el = $();
    $(this).nextUntil("h1").clone().appendTo(el);
});

But it doesn't work el doesn't contain element. Here I show you what is the structure of my HTML document.

<html>
<head>
</head>

<body>
    <h1 id="firstId">First H1 header</h1>
    <!-- Some text, tables, pictures -->

    <h1 id="secondId">Second H1 header</h1>
        <h2 id="thirdId">First H2 header</h2>
        <!-- Some text, tables, pictures -->

    ...
</body>
</html>

If you have some ideas or suggestions... Thank you =)

1

There are 1 answers

0
Muddasir Abbas On

Try this

$(function () {
    $('h1').each(function () {
        $(this).nextUntil('h1').add(this).wrapAll('<div />');
    });
});

and also this

$('#subgroup h3').each(function() {
    $(this).nextUntil('h3').wrapAll('<div id="myid" class="myclass"></div>');
});

references

Wrap HTML with DIV until next H3

How to wrap h1 and follow content in div?