I'm currently working on grouping every 3 divs with a class of search-audio inside a div with a class of slide.
The issue I'm facing is that it's giving me an error stating that elem.parentElement is undefined...
However, the initial part of the code is functioning correctly...
const audioBlocks = document.querySelectorAll('.search-audio');
const slider = document.querySelector('.slider');
const audioBlockArr = Array.from(audioBlocks);
function groupBlocks(arr, len) {
let groups = [],
i = 0,
n = arr.length;
while (i < n) {
groups.push(arr.slice(i, i += len));
}
return groups;
}
newArr = [...groupBlocks(audioBlockArr, 3)];
The main challenge lies in wrapping a div around the newly grouped elements array.
let wrap = (array) => {
array.forEach((elem) => {
let div = document.createElement('div');
div.classList.add('slide');
div.innerHTML = '';
elem.parentElement.insertBefore(div, elem);
div.appendChild(elem);
});
}
wrap(newArr);
Full code:
const audioBlocks = document.querySelectorAll('.search-audio');
const slider = document.querySelector('.slider');
const audioBlockArr = Array.from(audioBlocks);
function groupBlocks(arr, len) {
let groups = [],
i = 0,
n = arr.length;
while (i < n) {
groups.push(arr.slice(i, i += len));
}
return groups;
}
newArr = [...groupBlocks(audioBlockArr, 3)];
let wrap = (array) => {
array.forEach((elem) => {
let div = document.createElement('div');
div.classList.add('slide');
div.innerHTML = '';
elem.parentElement.insertBefore(div, elem);
div.appendChild(elem);
});
}
wrap(newArr);
body {
font-family: system-ui;
background: #f06d06;
color: white;
text-align: center;
}
.search-audio {
height: 12rem;
width: 12rem;
background: rgb(255, 153, 0);
margin: .5rem;
display: inline-block;
}
.slide {
background-color: #555;
}
<body>
<div class="slider">
<div class="search-audio 1"></div>
<div class="search-audio 2"></div>
<div class="search-audio 3"></div>
<div class="search-audio 4"></div>
<div class="search-audio 5"></div>
<div class="search-audio 6"></div>
<div class="search-audio 7"></div>
<div class="search-audio 8"></div>
<div class="search-audio 9"></div>
<div class="search-audio 10"></div>
<.....
......
></div>
</body>
</html>