Reputation: 461
Consider we have:
<div class "parent">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
// And Even More....
</div>
I need to Wrap each 3 or fewer (2 , 1), element into the ONE, while I don't know the count of child nodes. The result I need is something like:
<div class "parent">
<div class "middle">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>
<div class "middle">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>
<div class "middle">
<div class="child"></div>
</div>
// And Even More....
</div>
How to use .wrapAll()
or any other method to do this?
A better version of the question would be: How to Select div
's 3 by 3? as this post is showing how to wrap them.
Upvotes: 0
Views: 151
Reputation: 9393
Always try to get the total elements into variable. .length
value remains constant, it will not change for every iteration.
var childs = $("div.parent").children();
var totElements = childs.length;
var i = -3;
while( (i += 3) < totElements)
childs.slice(i,i+3).wrapAll( "<div class='middle' />");
Upvotes: 1
Reputation: 1876
var divs = $(".parent div.child");
var divs_length = divs.length;
for(var i = 0; i < divs_length; i+=3) {
divs.slice(i, i+3)
.wrapAll('<div class="middle"></div>');
}
Upvotes: 1