I am currently working with Bootstrap 5 (Beta 3 - no JQuery) on a static website, and I am facing the challenge of making a navbar link appear active. I prefer to achieve this using JavaScript instead of creating a separate navbar for each page. For instance, when the user visits the about.html page, I want the About link in the navbar to be highlighted as follows:
<li><a class="nav-link active" href="about.html">About</a></li>
HTML Snippet
<nav id="navbar" class="navbar">
<ul> <!-- "scrollto active" below -->
<li><a class="nav-link" href="index.html">Home</a></li>
<li><a class="nav-link" href="about.html">About</a></li>
<li><a class="nav-link" href="team.html">Your Team</a></li>
<li><a class="nav-link" href="services.html">Services</a></li>
<li><a class="nav-link" href="#footer">Contact</a></li>
<!-- <li><a class="nav-link" href="#"><strong>Client Login</strong></a></li> -->
</ul>
<i class="bi bi-list mobile-nav-toggle"></i>
</nav>
Current JS Code
var filename = window.location.pathname;
// This gives me: /about.html
var link = filename.substring(1, (filename.length-5));
//This gives me: about
var x = document.getElementsByTagName('ul')[0];//.getElementsByTagName("li")[0]; //.getElementsByTagName("a")[0]; // .getAttribute("href");
// I tried using the uncommented code with .getElementsByTagName("li").getElementsByTagname(a")[0].getAttribute("href")
// but I just get 5 NULLs (I have 5 links in the navbar)
var lists = x.children;
// This gives me an HTML Collection, right?
for (let i = 1; i < x.childElementCount; i++) {
console.log(lists[i]);
//What I want to do is check what the href text is
//Pseudocode:
//if (the_href_value == link variable) {
// add " active" to the <a> class
//}
console.log(lists[i].getAttribute("href"));
//this gives me NULL
};
I believe I am making progress, however, I have reached a point where I need some assistance to move forward.