尝试将 class 设置为下一个元素时出现问题

Problem when trying to set class to next element

我正在模态 window 中制作画廊,当我尝试将 class 设置为下一个元素时,它给出了错误“无法读取 属性 'classList' 为空”。我该如何解决这个问题?

HTML
<div class="card-page__imgs">
   <img id="1" href="assets/img/card-page-main-img.png" class="card-page__main-img gallery-img" 
   src="assets/img/card-page-main-img.png" alt="Изображение">
   <div class="card-page__img-group">
      <img id="2" src="assets/img/card-page-img1.png" class="card-page__second-img gallery-img next-img">
      <img id="3" src="assets/img/card-page-img2.png" class="card-page__second-img gallery-img">
      <img id="4" src="assets/img/card-page-img3.png" class="card-page__second-img gallery-img">
   </div>
</div>
JS
const galleryBtnPrev = document.querySelector('.gallery__btn_prev'),
    galleryBtnNext = document.querySelector('.gallery__btn_next'),
    galleryMainImg = document.querySelector('.gallery__main-img'),
    galleryImages = document.querySelectorAll('.gallery-img');

const showNext = () => {
    const galleryImagesArr = Array.from(galleryImages);
    galleryImagesArr.forEach((el, i) => {
        //if(el.classList.contains('next'))
        const nextSrc = el.getAttribute('src');
        if(el.classList.contains('next-img')) {
            galleryMainImg.setAttribute('src', nextSrc);
            el.classList.remove('next-img');
            // el.classList.add('next-img');
            const nextElem =el.nextElementSibling;
            console.log(nextElem);
            nextElem.classList.add('next-img');
            return false;
        }
        // console.log(el, i);
    });
};

您不能执行 const nextElem = el.nextElementSibling;,因为您已将 nodeList 转换为数组,因此 nextElementSibiling 属性 不起作用,但是您可以使用 [= 遍历 nodeList 13=] 无论如何,所以如果你删除 const galleryImagesArr = Array.from(galleryImages); 并只使用 galleryImages 代替 galleryImagesArr 它会起作用

编辑 错误是由于尝试在数组末尾的 when 读取下一个兄弟所以它返回 null 而不是包装到开始,用简单的 IF 语句

修复了这个问题

像这样

const galleryBtnPrev = document.querySelector('.gallery__btn_prev'),
    galleryBtnNext = document.querySelector('.gallery__btn_next'),
    galleryMainImg = document.querySelector('.gallery__main-img'),
    galleryImages = document.querySelectorAll('.gallery-img');

const showNext = () => {
    galleryImages.forEach((el, i) => {
        //if(el.classList.contains('next'))
        const nextSrc = el.getAttribute('src');
        if(el.classList.contains('next-img')) {
            //galleryMainImg.setAttribute('src', nextSrc);
            el.classList.remove('next-img');
            // el.classList.add('next-img');
            var nextElem = el.nextElementSibling
            if (nextElem === null) {
              nextElem = galleryImages[0]
            }
            nextElem.classList.add('next-img'); 
            return false;
        }
        // console.log(el, i);
    });
};
showNext()