I can not seem to find how to get this done proper.
const menu = document.querySelectorAll('.menu-item');
menu.forEach(item=>{
item.addEventListener('click', ()=>{
// now I need to select all menu items accept 'this' to remove 'is-active' class.
document.querySelector(".menu-link").classList.remove("is-active"); // not working
!this.classList.remove("is-active"); // not working
this.classList.add("is-active"); // add active class to menu item
});
});
I know I could again loop trough all items then remove for each item the class and last add for 'this', but I think there should be a way to select all but this.
Iterate over all menu items again - you're already doing forEach to add the listeners, so just do that again inside the listener. After that, reference the item (the item being iterated over) to add the class. (Using this won't work because you're using an arrow function.)
const menuItems = document.querySelectorAll('.menu-item');
menuItems.forEach(item => {
item.addEventListener('click', () => {
menuItems.forEach(item => {
item.classList.remove("is-active");
});
item.classList.add("is-active");
});
});
Or save the last active one in a variable
let lastActive;
const menuItems = document.querySelectorAll('.menu-item');
menuItems.forEach(item => {
item.addEventListener('click', () => {
lastActive?.classList.remove("is-active");
item.classList.add("is-active");
lastActive = item;
});
});
If you really want to go the comparison route, then
const menuItems = document.querySelectorAll('.menu-item');
menuItems.forEach(item => {
item.addEventListener('click', () => {
menuItems.forEach(innerItem => {
if (innerItem !== item) {
innerItem.classList.remove("is-active");
}
});
item.classList.add("is-active");
});
});
or if you must use this, don't use an arrow function.
const menuItems = document.querySelectorAll('.menu-item');
menuItems.forEach(item => {
item.addEventListener('click', function() {
menuItems.forEach(innerItem => {
if (innerItem !== this) {
innerItem.classList.remove("is-active");
}
});
this.classList.add("is-active");
});
});