Как добавить класс всем элементам коллекции и удалить класс у всех элементов?
let header = document.querySelector(".menu-ul");
let menuList = document.querySelectorAll(".list")
;
console.log(pageYOffset);
window.addEventListener("scroll",function(){
let y = this.pageYOffset;
if(y>1000){
header.classList.add("sticky")
for (let i = 0; i < menuList; i++) {
menuList.classList.toggle("sticky");
console.log(j);
}
}
else{
header.classList.remove("sticky")
}
})
Ответы (2 шт):
Автор решения: Евгений Кулик
→ Ссылка
вот так
let header = document.querySelector(".menu-ul");
let menuList = document.querySelectorAll(".list")
window.addEventListener("scroll",function(){
let y = this.pageYOffset;
if(y>1000){
header.classList.add("sticky")
for(let item of menuList) {
item.classList.add("sticky")
}
}
else{
header.classList.remove("sticky")
for(let item of menuList) {
item.classList.remove("sticky")
}
}
})
Автор решения: EzioMercer
→ Ссылка
Если разница только в добавлении и удалении классов, то можете написать так коротко:
const header = document.querySelector(".menu-ul");
const menuList = document.querySelectorAll(".list");
window.addEventListener("scroll", () => {
const y = this.pageYOffset;
const isBig = y > 1000;
const action = isBig ? 'add' : 'remove';
const className = 'sticky';
header.classList[action](className);
menuList.forEach(item => item.classList[action](className));
})