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

Time:04-10

I have the below structure:

<div >
    <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 >
    <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>" );

CodePudding user response:

  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>" );
        // move the h1 inside the wrapped div
        const el = $(this).next();
        $(this).prependTo(el);
    });
</script>

CodePudding user response:

I came up with this solution where it gets all the children and then if its a h1 tag it will create a new div and move H1 and other children into it

    var newDiv;
    $(document).ready(function(){
        $(".wrapper").children().each(function(){
           if($(this).is("h1")){
              $(this).before("<div></div>");
              newDiv =  $(this).prev();
              newDiv.append($(this));
           }else{
            newDiv.append($(this));
           }
        });
       
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >

        <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>

  • Related