How to select all elements between two identical elements?

in the div container I want to select and group all the headers with its contents until the next heading. These blocks should have a different background color.

This is what I got in my html:

<div class="container">
    <h2></h2>
    <p></p>
    <p></p>
    <ul></ul>
    <h2></h2>
    <p></p>
    <p></p>
    <p></p>
    <h2></h2>
    <p></p>
    <p></p>
    <p></p>
</div>

And I need this:

<div class="container">
    <div class="xy">
        <h2></h2>
        <p></p>
        <p></p>
        <ul></ul>
    </div>
    <div class="xy">
        <h2></h2>
        <p></p>
        <p></p>
        <p></p>
    </div>
    <div class="xy">
        <h2></h2>
        <p></p>
        <p></p>
        <p></p>
    </div>
</div>

I tried using nextUntil (), but so far this has not worked.

I would appreciate any help.

Best Robin

+4
source share
1 answer

This is the trick:

$('.container h2').each(function() {    //for each h2
  $(this)
    .nextUntil('h2')                    //get siblings until next h2, or all next siblings if no more h2
    .addBack()                          //include current h2
    .wrapAll('<div class="xy"/>');      //wrap it
});

$('pre').text($('.container').html());  //show it!
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
    <h2></h2>
    <p></p>
    <p></p>
    <ul></ul>
    <h2></h2>
    <p></p>
    <p></p>
    <p></p>
    <h2></h2>
    <p></p>
    <p></p>
    <p></p>
</div>
        
<pre></pre>
Run code
+8
source

Source: https://habr.com/ru/post/1614507/


All Articles