<style>
.images {
border: 1px blue solid;
padding: 10px;
}
.group {
border: 1px red solid;
padding: 10px;
margin: 5px 0;
}
img {
width: 20px;
height: 20px;
margin: 5px;
}
</style>
<body>
<div class="images">
<img class="p--img" src="images/p01.jpg" alt="">
<img class="p--img" src="images/p02.jpg" alt="">
<img class="p--img" src="images/p03.jpg" alt="">
<img class="p--img" src="images/p04.jpg" alt="">
<img class="p--img" src="images/p05.jpg" alt="">
<img class="p--img" src="images/p06.jpg" alt="">
<img class="p--img" src="images/p07.jpg" alt="">
<img class="p--img" src="images/p08.jpg" alt="">
<img class="p--img" src="images/p01.jpg" alt="">
<img class="p--img" src="images/p02.jpg" alt="">
<img class="p--img" src="images/p03.jpg" alt="">
<img class="p--img" src="images/p04.jpg" alt="">
<img class="p--img" src="images/p05.jpg" alt="">
<img class="p--img" src="images/p05.jpg" alt="">
</div>
<script>
const group = (dv, n) => {
let chim;
while ((chim = dv.querySelectorAll(':scope>.p--img')) && chim.length) {
const ng = Math.min(chim.length, n);
const dg = document.createElement('div');
dg.setAttribute('class', 'group');
dv.insertBefore(dg, chim[0]);
for (let i=0; i< ng; i++) dg.append(chim[i])
}
}
group (document.querySelector('.images'), 3)
</script>
</body>