I want to add .active class to <a>
tag depending on which page I'm currently on, so I can style it.
When I go to Home page, this should happen:
<li><a class="active" href="#">HOME</a></li>
<li><a href="#">ABOUT</a></li>
<li><a href="#">LOCATION</a></li>
When I go to About page, then this should happen:
<li><a href="#">HOME</a></li>
<li><a class="active" href="#">ABOUT</a></li>
<li><a href="#">LOCATION</a></li>
Etcetra...
This image describes what I'm trying to achieve:
const currentLocation = location.href;
const menuItem = document.querySelectorAll('a');
const menuLength = menuItem.length
for (let i = 0; i<menuLength; i++){
if(menuitem[i].href === currentLocation){
menuItem[i].className = "active"
}
}
ul li a {
color: black;
background-color: silver;
}
ul li a.active {
color: white;
background-color: black;
}
<nav class="navbar">
<div class="navbar-links">
<ul>
<li><a href="http://example.com/home/">HOME</a></li>
<li><a href="http://example.com/about/">ABOUT</a></li>
<li><a href="http://example.com/location/">LOCATION</a></li>
</ul>
</div>
</nav>
It just doesn't work. Any suggestions?