<div class="wrap">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
<div class="item">6</div>
<div class="item">7</div>
<div class="item">8</div>
<div class="item">9</div>
<div class="item">10</div>
<div class="item">11</div>
<div class="item">12</div>
<div class="item">13</div>
<div class="item">14</div>
<div class="item">15</div>
<div class="item">16</div>
</div>
<div class="wrap">
<div class="wrap-item">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
</div>
<div class="wrap-item">
<div class="item">5</div>
<div class="item">6</div>
<div class="item">7</div>
<div class="item">8</div>
</div>
<div class="wrap-item">
<div class="item">9</div>
<div class="item">10</div>
<div class="item">11</div>
<div class="item">12</div>
</div>
<div class="wrap-item">
<div class="item">13</div>
<div class="item">14</div>
<div class="item">15</div>
<div class="item">16</div>
</div>
</div>
const parentSelector = '.wrap';
const wrapperTag = 'div';
const wrapperClass = 'wrap-item';
const wrapSize = 4;
const $items = $(parentSelector).children();
for (let i = 0; i < $items.length; i += wrapSize) {
$items.slice(i, i + wrapSize).wrapAll(`<${wrapperTag} class="${wrapperClass}">`);
}
const parent = document.querySelector(parentSelector);
const items = [...parent.children];
parent.append(...Array.from(
{ length: Math.ceil(items.length / wrapSize) },
(n, i) => {
const wrapper = document.createElement(wrapperTag);
wrapper.classList.add(wrapperClass);
wrapper.append(...items.slice(i * wrapSize, (i + 1) * wrapSize));
return wrapper;
}
));