Wrap three repeating div groups into one using jQuery

I have one more problem. I have few repeating div groups. In one group there are 3 divs with different classes.

What I need to do is wrap in one β€œcontainer”. When I use wrapAll, it wraps everything in 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> 

It is all in one body.

As a result, I would like them to 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> 

Thanks for your help in advance.

+4
source share
4 answers

I only wrote a 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 an options object defining

  • childElem - filter selector for immediate children to carry
  • sets how you want to group the children. For example, sets of 3 in your case. Default 1
  • wrapper - an element for wrapping children. default - <div>

Use your data the same way. You must define a parent for 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

+7
source

Assuming your div is all children with an id container (otherwise change the jquery selector) and they look strictly in that order

 while ($("#container > div[class^='bb_box_']").size() >= 3) $("#container > div[class^='bb_box_']:lt(3)").wrapAll("<div class='box-cont'></div>"); 
+2
source

This is a bit confusing, but I could not come up with an easier way. It works though:

 $("div.bb_box_tl").wrap("<div class='box-cont'></div>"); $("div.box-cont").each(function() { $(this).append($(this).next()); $(this).append($(this).next()); }); 
+1
source

I am not an expert, but this might work:

 $(".bb_box_tl").before('<div class="box-cont">'); $(".bb_box_lb").after('</div>'); 
-1
source

Source: https://habr.com/ru/post/894252/


All Articles