I'm looking to add an active element class to my navbar, when I select the next link the previous one stays highlighted, I just want the current link to remain active.
See code below:
<header>
<nav>
<ul>
<li><a href="#">home</a></li>
<li><a href="#">about</a></li>
<li><a href="#">service</a></li>
<li><a href="#">profile</a></li>
<li><a href="#">portfolio</a></li>
<li><a href="#">contact</a></li>
</ul>
</nav>
</header>
document.querySelectorAll('li').forEach(item => {
item.addEventListener('click', event => {
alert(item.outerHTML);
if(item.className === "active"){
item.classList.remove("active");
}
item.classList.add("active");
});
})
You could remove active class from all li element and add the active class to the current one
document.querySelectorAll('li').forEach(item => {
item.addEventListener('click', event => {
document.querySelectorAll('li').forEach(i => {i.classList.remove('active')})
item.classList.add('active')
})
})
If you want to use for loops
for(let item of document.querySelectorAll('li')) {
item.addEventListener('click', event => {
// Remove active class from all li
for(let i of document.querySelectorAll('li')) {
i.classList.remove('active')
}
item.classList.add('active')
})
}
because the item in the event is target to this
document.querySelectorAll('li').forEach(item => {
item.addEventListener('click', event => {
alert(item.outerHTML);
document.querySelectorAll('li').forEach(item => {
if(item.className === "active"){
item.classList.remove("active");
}
});
item.classList.add("active");
});
})