<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="wrapper">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
<div class="box"></div>
<div class="box"></div>
const parent = document.querySelector('.box').parentNode;
const iMin = 2;
const iMax = 5;
const wrapper = document.createElement('div');
wrapper.classList.add('wrapper');
if (parent.children[iMin]) {
const elems = Array.prototype.slice.call(parent.children, iMin, iMax);
elems[0].before(wrapper);
wrapper.append(...elems);
}
// или
const elems = parent.querySelectorAll(`:nth-child(n + ${-~iMin}):not(:nth-child(n + ${-~iMax}))`);
if (elems.length) {
parent.insertBefore(wrapper, elems[0]);
elems.forEach(n => wrapper.appendChild(n));
}
// или
if (parent.children.length > iMin) {
parent.children[iMin].insertAdjacentElement('beforebegin', wrapper);
for (let i = iMax - iMin, n = null; i-- && (n = wrapper.nextElementSibling);) {
wrapper.insertAdjacentElement('beforeend', n);
}
}
const boxes = document.querySelectorAll('.box');
const isNested = (f, t, c) => c + 1 >= f && c + 1 <= t;
const insertAfter = (elem, refElem) => refElem.parentNode.insertBefore(elem, refElem.nextSibling);
const transferBoxesToWrapper = (fromIndex, toIndex, wrapper) => {
boxes.forEach((box, i) => isNested(fromIndex, toIndex, i) && wrapper.appendChild(box));
}
const createWrapper = (fromIndex, toIndex) => {
let wrapper = document.createElement('div');
wrapper.classList.add('wrapper');
insertAfter(wrapper, boxes[fromIndex - 1]);
transferBoxesToWrapper(fromIndex, toIndex, wrapper);
}
createWrapper(3, 5);
let wrapper = document.createElement('div')
wrapper.className = 'wrapper'
wrapper.appendChild(document.querySelector(`.box:nth-of-type(3)`))
wrapper.appendChild(document.querySelector(`.box:nth-of-type(3)`))
wrapper.appendChild(document.querySelector(`.box:nth-of-type(3)`))
document.querySelector('.box:nth-of-type(2)').after(wrapper)