Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

add active class and remove active class by click

/*
Here are some HTML codes looks like
<ul class="navbar-nav m-auto mb-2 pb-lg-0 main_menu">
              <li class="nav-item position-relative me-5">
                <a class="nav-link active" aria-current="page" href="#">Home</a>
              </li>
              <li class="nav-item me-5">
                <a class="nav-link" href="#">About</a>
              </li>
              <li class="nav-item me-5">
                <a class="nav-link" href="#">Elements</a>
              </li>
              <li class="nav-item me-5">
                <a class="nav-link" href="#">Blogs</a>
              </li>
              <li class="nav-item me-5">
                <a class="nav-link" href="#">Portfolio</a>
              </li>
              <li class="nav-item me-5">
                <a class="nav-link" href="#">Contact</a>
              </li>
              
            </ul>
*/

// Here are javascript code looks like
const links = document.querySelectorAll(".nav-link");

links.forEach((link)=> {
    link.addEventListener("click", function(){
        links.forEach((e)=> {e.classList.remove('active')})
        this.classList.add('active')
    })
})
 
PREVIOUS NEXT
Tagged: #add #active #class #remove #active #class #click
ADD COMMENT
Topic
Name
3+2 =