I have a cms that lets users insert blocks of content on a page. There are different types of content block available to the user and they can be inserted in any order. An example high-level dom structure might look something like this:
<p>Some rich text</p>
<div class="box">...</div>
<div class="box">...</div>
<div class="box">...</div>
<h3>Some more rich text</h3>
<p>Lorem ipsum</p>
<div class="box">...</div>
<div class="box">...</div>
What I want to do is wrap any adjacent 'box' divs in a wrapping 'container' div. So in the example above there would be two 'container' divs inserted as there are two groups of box divs, resulting in:
<p>Some rich text</p>
<div class="container">
<div class="box">...</div>
<div class="box">...</div>
<div class="box">...</div>
</div>
<h3>Some more rich text</h3>
<p>Lorem ipsum</p>
<div class="container">
<div class="box">...</div>
<div class="box">...</div>
</div>
I don't think there is a clever way to do it with css selectors, so does anyone know of anyway to do this with jQuery?
You can use
.nextUntil
, to get all the next .box
..andSelf
to add the current element to the collection.wrapAll
to wrap each collection to a different .container
$('.box').not('.box+.box').each(function(){
$(this).nextUntil(':not(.box)').addBack().wrapAll('<div class="container" />');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Some rich text</p>
<div class="box">...</div>
<div class="box">...</div>
<div class="box">...</div>
<h3>Some more rich text</h3>
<p>Lorem ipsum</p>
<div class="box">...</div>
<div class="box">...</div>
http://jsbin.com/gonino/edit?html,js
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