M
M
MyQuestion2021-06-23 11:39:03
JavaScript
MyQuestion, 2021-06-23 11:39:03

Why remove only removes the class from the last element of the array?

Good afternoon!

I need to remove the class for all array elements.
What am I doing:

const galleryItems = document.querySelectorAll('.gallery__slide');
let addSwiper;
let removeSwiper;

for (var i = 0; i < galleryItems.length; i++) {
  let galleryItem = galleryItems[i];
  addSwiper = function () {
    galleryItem.classList.add('swiper-slide');
  }
  removeSwiper = function () {
    console.log('false');
    galleryItem.classList.remove('swiper-slide');
  }
}


Remove will remove and add a class to only the last element of the array. I know that for remove you can specify which element it will remove, for example remove[3], if this is not specified, apparently it will take only the last element. I saw a solution with a call to the parent and did a loop through the children, something like items.children[i].remove('').

How it works?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alex, 2021-06-23
@MyQuestion

This is because each iteration of the loop overwrites the addSwiperand removeSwiper. As a result, after the end of the loop, the functions that were written there during the last iteration remain in these variables - that is, for processing the last element of the array.

D
Denis Sokolov, 2021-06-23
@Denis147258369

Seems like it should work

const galleryItems = document.querySelectorAll('.gallery__slide');

for (let i = 0; i < galleryItems.length; i++) {
  let galleryItem = galleryItems[i];
  addSwiper(galleryItem)
  removeSwiper(galleryItem)
}

function addSwiper(item) {
  console.log('Добавили', item.dataset.id)
  item.classList.add('swiper-slide');
}

function removeSwiper(item) {
  console.log('Удалили', item.dataset.id)
   item.classList.remove('swiper-slide');
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question