Search code examples
javascriptjquerytraversalsiblings

Get all elements between element type (h1's) and wrap in div


I have the below structure:

<div class="wrapper">
    <h1>Header 1</h1>
    <h2>subtitle 1</h2>
    <p>aaa</p>
    <p>bbb</p>
    <p>ccc</p>
    <h2>subtitle2</h2>
    <p>ddd</p>

    <h1>Header 2</h1>
    <h2>subtitle 3</h2>
    <p>eee</p>
    <p>fff</p>

</div>

I want to select all the h1 and p elements between each h1 and wrap in a div, so I end up with:

<div class="wrapper">
    <div>
        <h1>Header 1</h1>
        <h2>subtitle 1</h2>
        <p>aaa</p>
        <p>bbb</p>
        <p>ccc</p>
        <h2>subtitle2</h2>
        <p>ddd</p>
    </div>

    <div>
        <h1>Header 2</h1>
        <h2>subtitle 3</h2>
        <p>eee</p>
        <p>fff</p>
    </div>
</div>

I've tried various things like the below, but none work perfectly:

$( "h1" ).prevUntil( "h1" ).wrapAll( "<div></div>" );

Solution

    1. You shall use .each jQuery API to accomplish.
    $("h1").each(function(){})
    
    1. .prevUntil will inverse the Dom node traversing, use .nextUntil instead.

    2. as to match the end-up output, the script is as follows:

    <script>
        $("h1").each(function() {
            $(this).nextUntil( "h1" ).wrapAll( "<div></div>" );
            // uncomment the two lines to move the h1 inside the wrapped div
            // const el = $(this).next();
            // $(this).prependTo(el);
        });
    </script>