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
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With