lshettyl
lshettyl

Reputation: 8181

wrapping elements in a new div

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

Upvotes: 1

Views: 280

Answers (4)

RightSaidFred
RightSaidFred

Reputation: 11327

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/

Upvotes: 2

Idris Mokhtarzada
Idris Mokhtarzada

Reputation: 1044

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];
}

Upvotes: 0

BenSho
BenSho

Reputation: 130

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.

Upvotes: 0

Related Questions