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:

