Wrap three repeating div groups into one using jQuery
jquery
Solution
I wrote just the plugin for this a while ago
(function($){
$.fn.wrapChildren = function(options) {
var options = $.extend({
childElem : undefined,
sets : 1,
wrapper : 'div'
}, options || {});
if (options.childElem === undefined) return this;
return this.each(function() {
var elems = $(this).children(options.childElem);
var arr = [];
elems.each(function(i,value) {
arr.push(value);
if (((i + 1) % options.sets === 0) || (i === elems.length -1))
{
var set = $(arr);
arr = [];
set.wrapAll($("<" + options.wrapper + ">"));
}
});
});
}
})(jQuery);
You pass in an options object defining
- childElem - the filter selector of the immediate children to wrap
- sets - how you want to group the child elements. For example, sets of 3 in your case. Default is 1
- wrapper - the element to wrap the child elements in. default is `<div>`
Use like so on your data. You need to define a parent element for the divs
$(function() {
$('body').wrapChildren({
childElem : 'div.bb_box_tl, div.bb_box_l, div.bb_box_lb' ,
sets: 3,
wrapper: 'div class="box-cont"'
});
});
Here's a Working Demo with some data.
UPDATE:
I wrote a blog post with a slightly modified and improved version of this
Problem
I have another problem here. I have few repeating groups of divs. There is 3 divs with different classes in one group. What I need to do is wrap the into one 'container'. When I'm using wrapAll it wraps all into one div. And this is my html: ``` <div class="bb_box_tl"></div> <div class="bb_box_l"></div> <div class="bb_box_lb"></div> <div class="bb_box_tl"></div> <div class="bb_box_l"></div> <div class="bb_box_lb"></div> <div class="bb_box_tl"></div> <div class="bb_box_l"></div> <div class="bb_box_lb"></div> ``` This is all in one body. As I result i would like to have them look like this: ``` <div class="box-cont"> <div class="bb_box_tl"></div> <div class="bb_box_l"></div> <div class="bb_box_lb"></div> </div> <div class="box-cont"> <div class="bb_box_tl"></div> <div class="bb_box_l"></div> <div class="bb_box_lb"></div> </div> <div class="box-cont"> <div class="bb_box_tl"></div> <div class="bb_box_l"></div> <div class="bb_box_lb"></div> </div> ``` Thank you for your help in advance