Open In App

How to have the class=“selected” depending on what the current page/url is ?

Having class = “selected” depending on what page / URL is. This concept is very important especially when designing a navbar for a website so that visitors on the website know on which page of the site they are on

Approach: To have class=” selected” depending on what the current page/URL is :



Syntax:

const currentLocation = location.href

Example: This code should be pasted in all the 4 files.






<html>
  <head>
    <style>
      a {
        color: #000;
        text-decoration: none;
      }
  
      .nav {
        padding: 10px;
        border: solid 1px #c0c0c0;
        border-radius: 5px;
        float: left;
      }
      .nav li {
        list-style-type: none;
        float: left;
        margin: 0 10px;
      }
      .nav li a {
        text-align: center;
        width: 55px;
        float: left;
      }
      .nav li a.selected {
        background-color: green;
        color: #fff;
        font-weight: bold;
      }
    </style>
  </head>
  
  <body>
    <ul class="nav">
      <li><a href="home.html">Home</a></li>
      <li>|</li>
      <li><a href="gfg.html">GFG</a></li>
      <li>|</li>
      <li><a href="about.html">About</a></li>
      <li>|</li>
      <li><a href="contact.html">Contact</a></li>
    </ul>
  </body>
  <script type="text/javascript">
    const currentLocation = location.href;
    const Items = document.querySelectorAll("a");
    const Length = Items.length;
  
    for (let i = 0; i < Items.length; i++) {
      if (Items[i].href === currentLocation) {
        Items[i].className = "selected";
      }
    }
  </script>
</html>

Output:


Article Tags :