Answer the question
In order to leave comments, you need to log in
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');
}
}
items.children[i].remove('')
. Answer the question
In order to leave comments, you need to log in
This is because each iteration of the loop overwrites the addSwiper
and 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.
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 questionAsk a Question
731 491 924 answers to any question