Home > Blockchain >  Nav bar Active tab color change
Nav bar Active tab color change

Time:10-03

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

<nav class="navbar">
    <ul>
        <li class="nav-list"><a href="home.html" class="navlink">Home</a></li>
        <li class="nav-list"><a href="aboutme.html" class="navlink">About me</a></li>
        <li class="nav-list"><a href="work.html" class="navlink">Work</a></li>
        <li class="nav-list"><a href="contact.html" class="navlink">Contact me</a></li>
    </ul>
</nav>

css

.nav-list a.active{
    color:rgb(28, 162, 224);
}

javaScript

const currentlocation = location.href;
const menuitem = document.querySelectorAll('nav-list a');
const menulenght = menuitem.length;

for(let i = 0; i < menulenght; i  ){
    if(menuitem[i].href === currentlocation){
        menuitem[i].className =  'active';
    }
}

CodePudding user response:

1) You have to use . for class selector as:

document.querySelectorAll( '.nav-list a' );

2) You have to use add method to add a new class as:

menuitem[i].classList.add( "active" )

JS

const currentlocation = location.href;
const menuitem = document.querySelectorAll( '.nav-list a' );

for ( let i = 0; i < menuitem.length; i   ) {
    if ( menuitem[i].href === currentlocation ) {
        menuitem[i].classList.add( "active" )
    }
}

Also, there is a typo in your current code: lenght instead of length

  • Related