Creating an Active Link in Bootstrap 5.0 (Beta 3) Navbar Using JavaScript

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.

Answer №1

Seems like a simplification could be achieved by...

let pageURL = window.location.pathname;
let linkName = pageURL.slice(1, -5);
let navigationLink = document.querySelector('[href^='+linkName+']');
navigationLink.classList.add('active');

Example Demo

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why does my window scroll change when making a $.ajax call?

Encountering a peculiar bug... Whenever my JS code enters the success function after a jQuery $.ajax call, the scroll position on my window suddenly jumps to the bottom of the page. This is problematic for me as I'm developing a mobile page and want t ...

Learn how to efficiently redirect users without losing any valuable data after they sign up using localStorage

I am currently facing an issue with my sign up form. Whenever a user creates an account, I use localStorage to save the form values. However, if the user is redirected to another page after hitting the submit button, only the last user's data is saved ...

Fade-in a new, revised text after fading-out the original text in ReactJS

I have a bunch of p elements that I'd like to cycle through, fading in one at a time and then replacing it with the next. Here is the jQuery example on CodePen: https://codepen.io/motion333/pen/EBBGVM Now, I'm attempting to achieve the same effe ...

ObjectID is failing to store the hexadecimal values properly

Initially, the ObjectID in my Sails/Mongo database was stored like this: "_id" : ObjectId("557077fb836bdee256004232") However, something changed or happened, and now new records are stored differently: "_id" : { "_bsontype" : "ObjectID", "id" : ...

Issues with Bootstrap Modal Checkbox Functionality

Issue with Bootstrap modal checkbox functionality when the checkbox is selected The desired behavior is for the bootstrap modal popup to be triggered upon clicking the checkbox Bootstrap Version: 3.3.6 Jquery Version: 2.1.3 $(function() { $(&ap ...

What is the process for obtaining authorization to access user information?

I am facing a perplexing issue with my app settings. Despite setting everything up correctly, I am unable to authenticate my account on my website using the Javascript SDK. Whenever I try to console.log(me), I only receive public information. Upon furthe ...

`The challenge of a single web page not displaying correctly`

I was working on a website for a local computer building company, and I decided to make it a single-page applet. The HTML is mostly done, and I don't have much trouble with CSS. However, I encountered an issue with hiding and displaying different sect ...

What could be causing JQuery to disrupt my HTML code by inserting additional <a> tags?

My dilemma involves this specific chunk of HTML code stored within a javascript string, while utilizing Jquery 1.6.1 from the Google CDN: Upon executing console.log(string): <a><div class='product-autocomplete-result'> & ...

Leverage NodeJS data within Angular framework

I am working with the following route: Server app.get('/claim/:id', compact.js(['global']), indexController.claim); module.exports.claim=function(req,res){ res.render('claim-note', { title: 'claim', noteId:req. ...

Leveraging JavaScript for pricing calculations within asp.net framework

I am currently working with a textbox in a gridview and trying to calculate values using JavaScript. My code seems to be error-free. The goal is to multiply the quantity by the rate to get the total price. function totalise(price, rate, qt) { var qt ...

Unable to insert HTML code into a div upon clicking an image button

I am in the process of developing a website dedicated to radio streams, and I was advised to utilize Jquery and AJAX for loading HTML files into a div upon button click. This way, users wouldn't have to load an entirely new page for each radio stream. ...

Is it possible to interpret all events from multiple perspectives?

Is it possible to listen for events in three different ways? This example shows how we can listen for the load event: 1. <body onload="doSomething();"> 2. document.body.onload = doSomething; 3. document.body.addEventListener('load', doS ...

Double quotes in JSON are not being escaped properly

When I try to evaluate some json on a screen, I keep encountering errors with the message 'unexpected identifier'... The problematic data that seems to be causing this issue is: "itemDescription":"STANDARD \"B\" RED BOX", To address ...

interactive symbols in a reorganizable tree structure

I have been developing a customizable tree list for our users to arrange their website content. It allows them to add and rearrange pages by dragging and dropping. Each list item includes the page name and three icons (lock, visible, and edit). The challe ...

What is the best way to utilize MongoDB aggregate in this particular scenario?

How can I optimize this mongoose query to improve performance and reduce size for production? const currentYear = (new Date).getFullYear() const usedCars = await CarModel.find({ ModelYear: {$lte: currentYear - 1} }).limit(10) const recentCars = await Car ...

Removing redundant names from an array using Typescript

My task involves retrieving a list of names from an API, but there are many duplicates that need to be filtered out. However, when I attempt to execute the removeDuplicateNames function, it simply returns an empty array. const axios = require('axios&a ...

Tips for modifying a state array in Vuex

I have the ability to add and remove entries, but I'm struggling with editing. How can I achieve this using VUEJS, VUEX, and JavaScript? For adding entries, I know I should use PUSH, and for removing entries, SPLICE works fine. But what about editing ...

Mastering ReactJs: The Ultimate Guide to Updating State Properties

I've been attempting to change the isSelected property for a specific row in my state data, but am finding that it's not updating. Can someone please offer guidance on the most effective approach to achieve this? var selecte ...

Is handlebars.js giving you trouble all of a sudden?

My handlebars.js template was working perfectly for a week, but suddenly stopped. I'm puzzled by this issue and would appreciate any insights on why it might have stopped functioning. Here is the template: <script id="banners-template" type=" ...

Transform the componentDidUpdate method that uses prevProps into a custom hook integrated with Redux

Trying to convert a life cycle method into a hook is not working as expected. When the component mounted, if the user ID exists in local storage, the user is connected and their name is displayed in the navbar. If they disconnect and reconnect, their name ...