My code is not working I don’t know why?
someone, please help me out.
I am not able to add a class name to the active nav bar
JavaScript
x
9
1
<nav class="navbar">
2
<ul>
3
<li class="nav-list"><a href="home.html" class="navlink">Home</a></li>
4
<li class="nav-list"><a href="aboutme.html" class="navlink">About me</a></li>
5
<li class="nav-list"><a href="work.html" class="navlink">Work</a></li>
6
<li class="nav-list"><a href="contact.html" class="navlink">Contact me</a></li>
7
</ul>
8
</nav>
9
css
JavaScript
1
4
1
.nav-list a.active{
2
color:rgb(28, 162, 224);
3
}
4
javaScript
JavaScript
1
10
10
1
const currentlocation = location.href;
2
const menuitem = document.querySelectorAll('nav-list a');
3
const menulenght = menuitem.length;
4
5
for(let i = 0; i < menulenght; i++){
6
if(menuitem[i].href === currentlocation){
7
menuitem[i].className = 'active';
8
}
9
}
10
Advertisement
Answer
1) You have to use .
for class selector as:
JavaScript
1
2
1
document.querySelectorAll( '.nav-list a' );
2
2) You have to use add
method to add a new class as:
JavaScript
1
2
1
menuitem[i].classList.add( "active" )
2
JS
JavaScript
1
9
1
const currentlocation = location.href;
2
const menuitem = document.querySelectorAll( '.nav-list a' );
3
4
for ( let i = 0; i < menuitem.length; i++ ) {
5
if ( menuitem[i].href === currentlocation ) {
6
menuitem[i].classList.add( "active" )
7
}
8
}
9
Also, there is a typo in your current code: lenght
instead of length