Wrapping a div around every three divs
Let's say I have 6 children and they have no unique identifiers:
<div class="child"></div> <div class="child"></div> <div class="child"></div> <div class="child"></div> <div class="child"></div> <div class="child"></div> In jQuery, I want to wrap each set of 3 with <div class="parent"></div> . So it will look like:
<div class="parent"> <div class="child"></div> <div class="child"></div> <div class="child"></div> </div> <div class="parent"> <div class="child"></div> <div class="child"></div> <div class="child"></div> </div> What is the easiest way to do this?
+6
3 answers
Wow, good tricky question =)
while(($children = $(':not(.parent)>.child:lt(3)')).length) { $children .parent() .append( $('<div class="parent"></div>') .append($children.remove()) ); } Edit: didn't know about wrapAll method, therefore:
while(($children = $(':not(.parent)>.child:lt(3)')).length) { $children.wrapAll($('<div class="parent"></div>')); } +10
There's a little plugin that I wrote that I use in scripts like this. He takes the collection and breaks it into pieces x (where x is the size of each fragment):
$.fn.chunk = function( cLen ) { var chunks = []; while ( this.length ) { chunks.push( this.splice(0, cLen) ); } return $(chunks); }; Then it can be used as follows:
$('.child').chunk(3).each(function() { $(this).wrapAll('<div class="parent">'); }); Here is the violin
Or, as a plugin for this purpose:
$.fn.wrapEvery = function( cLen, wrapperEl ) { while ( this.length ) { $( this.splice(0, cLen) ).wrapAll( wrapperEl ); } }; What can be used as follows:
$('.child').wrapEvery(3, '<div class="parent">'); Here is another fiddle
+4