Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery wrapping groups of adjacent elements

Tags:

jquery

dom

css

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?

like image 707
benb Avatar asked Mar 15 '13 11:03

benb


1 Answers

You can use

  1. .nextUntil, to get all the next .box.
  2. .andSelf to add the current element to the collection
  3. .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

like image 86
Mosh Feu Avatar answered Nov 08 '22 17:11

Mosh Feu