Saturday, October 25, 2025
HomeLanguagesJavascriptHow to have the class=“selected” depending on what the current page/url is...

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 :

  • Write your HTML code.
  • Write the CSS for the selected class.
  • In javascript, Find the current location of your page using location.href .
  • Now save all the a tags in a variable lets say “Items” using document.querySelector function.
  • Iterate over the Items and compare its location with the current page URL.
  • If the Items location matches with the current location of the page the add the current a tag class to the selected class.

Syntax:

const currentLocation = location.href

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

HTML




<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:

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS