1

I have the below html:


<div id="one">
    <div class="two">
        <div class="entry">
        Content here
        </div>
        <div class="entry">
        Content here
        </div>
        <div class="entry">
        Content here
        </div>
        <div class="entry">
        Content here
        </div>
        <div class="entry">
        Content here
        </div>
        <div class="entry">
        Content here
        </div>
        <div class="entry">
        Content here
        </div>
        <div class="entry">
        Content here
        </div>
        <div class="entry">
        Content here
        </div>
    </div>
</div>

in jQuery if I am to wrap every 3 elemnts in a new div like below how could I do that?


<div id="one">
    <div class="two">
        <div>
            <div class="entry">
            Content here
            </div>
            <div class="entry">
            Content here
            </div>
            <div class="entry">
            Content here
            </div>
        </div>
        </div>
            <div class="entry">
            Content here
            </div>
            <div class="entry">
            Content here
            </div>
            <div class="entry">
            Content here
            </div>
        </div>
        <div>
            <div class="entry">
            Content here
            </div>
            <div class="entry">
            Content here
            </div>
            <div class="entry">
            Content here
            </div>
        </div>
    </div>
</div>

I tried slice and wrap which did not really help me. Any ideas? appreciate your help on this.

Thanks, L

lshettyl
  • 8,166
  • 4
  • 25
  • 31

4 Answers4

2
var entries = $('#one > .two > div.entry');

entries.each(function(i) {
    if( i % 3 == 0 ) entries.slice(i,i+3).wrapAll('<div>');
});

http://jsfiddle.net/PZkSL/

RightSaidFred
  • 11,209
  • 35
  • 35
0

Refer to this How to wrap every 3 child divs with html using jquery? or Wrap every 3 divs in a div

Community
  • 1
  • 1
jsweazy
  • 1,623
  • 9
  • 22
0

How about getting the div element with class "two", and iterate through it's children. When you find the first child use $(firstChild).before('<div>'); and on the third child use $(thirdChild).after('</div>'); Just iterate all the way through using this method. Haven't used .before() or .after() so not sure how this will pan out. Good luck.

BenSho
  • 130
  • 4
0

I would just write a simple for loop, something like:

var two = $(".two");
var elements = $(".entry");
var group = [];
for(var i=0;i<elements.length;i++) {
  var mod = i % 3;
  if(mod == 0 && group.length > 0) {
    var container = $('<div></div>');
    two.append(container);
    for(var j=0;j<group.length;j++) {
      container[0].appendChild(group[j]);
    }
    group = [];
  }
  group[mod] = elements[i];
}
Idris Mokhtarzada
  • 1,034
  • 12
  • 21