Ben10 Ben10 - 6 months ago 21
Javascript Question

How to add div dynamically inside of another div jquery?

I have a content like this

<div class="maindiv">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>


now I need to add div like this format

<div class="maindiv">
<div>
<div class="box"></div>
<div class="box"></div>
</div>
<div>
<div class="box"></div>
<div class="box"></div>
</div>



how to do this in jquery?

Answer

Try this

var boxes = $(".maindiv > .box");

for (var i = 0, len = boxes.length; i < len; i += 2) {
  boxes.slice(i, i + 2).wrapAll("<div></div>");
}

Example

Comments