I have some div elements that have a '.swiper-slide' class. I need this class to be removed on the mobile version of the screen. However, I am getting the error. Cannot read properties of undefined (reading 'classList')Please tell me how to fix it My js:
function overlay() {
let swiperSlide = document.querySelectorAll('.swiper-slide');
if (window.innerWidth < 991) {
swiperSlide.forEach((swip, index) => {
swip[index].classList.remove('swiper-slide');
});
} else {
swiperSlide.forEach((swip, index) => {
swip[index].classList.add('swiper-slide');
});
}
};
overlay();
This is wrong:
swip[index].classList.remove('swiper-slide');
In the callback to forEach, the first argument (in this case swip) isn't a copy of the array over which you're iterating. It's the individual element for any given iteration over the list. So you'd access it directly:
swip.classList.remove('swiper-slide');
If you wanted to use the index (the second argument to the callback) then you'd use that on the array, not the element:
swiperSlide[index].classList.remove('swiper-slide');