Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select all elements between two same elements?

in a div-container I want to select and group all headlines with its content until the next headline. 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 what I need is 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 it didn't work for me so far.

I would appreciate any help.

Best, Robin

like image 862
shroomlife Avatar asked Feb 08 '23 15:02

shroomlife


1 Answers

This does 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>
like image 197
Rick Hitchcock Avatar answered Feb 11 '23 15:02

Rick Hitchcock