How can I add an active CSS class to an li element depending on the href attribute of its child <a> tag?

Looking for a way to dynamically add an 'active' class to a navigation menu item based on the current URL? Here's what I have so far:

<ul class="nav sf-menu">
    <li><a href="@Url.Action("Index","Home")">Home<span></span></a></li>

In order to achieve this, I've attempted the following jQuery code:

$(function () {

    var url = window.location.pathname,
        urlRegExp = new RegExp(url.replace(/\/$/, '') + "$"); 
   
    $('.sf-menu li').each(function () {
        
        if (urlRegExp.test($(this).find('a').attr('href').replace(/\/$/, ''))) {
            $(this).addClass('active');
        }
    });

});

However, I encountered an error stating that 'li' does not have a 'href'. How can I resolve this issue and make it work as intended?

Answer №1

The href attribute is associated with the <a> element, not the <li> element. To target the correct element, you should check for the href within the <a> tag and then add the class to its parent <li>.

Below is an adjusted version of your code that focuses on selecting the <a> tag:

jQuery(function () {
    var url = window.location.pathname;

    if (url == '/') {
        jQuery('.sf-menu li > a[href="/"]').parent().addClass('active');
    } else {
        var urlRegExp = new RegExp(url.replace(/\/$/, '') + "$");
        jQuery('.sf-menu li > a').each(function () {
            if (urlRegExp.test(this.href.replace(/\/$/, ''))) {
                jQuery(this).parent().addClass('active');
            }
        });
    }
});

JSFiddle

I've also added a condition to handle cases where the link is set to / to prevent all links from being mistakenly marked as active.

If your links are simple enough, you can try this more straightforward version:

jQuery(function () {
    var url = window.location.pathname;
    jQuery('.sf-menu li > a[href="' + url + '"]').parent().addClass('active');
});

Answer №2

give this a shot

$('.sf-menu li >a').forEach(function () {

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

Ensure that the vue-router guard waits for the completion of the axios API call in Vuex before proceeding

I am currently working with a django-rest-axios-vuejs application stack, and I have a specific task that involves the vue-router. Within the beforeEach guard of the vue-router, I am checking permissions by verifying something in the me object within the v ...

Mongoose encountered a RangeError due to exceeding the maximum call stack size

I need to bulk insert documents into MongoDB using the native driver instead of Mongoose to enhance the writing speed. Mongoose does not support bulk insert of an array of documents, prompting me to bypass it. However, I encountered the "RangeError: Maxim ...

Tips for choosing the injected HTML's List Element (li) while ensuring it remains concealed

How do I hide the list item with iconsrc="/_layouts/15/images/delitem.gif" image when this div is injected by a first party and I am a third party trying to conceal it? $("<style> what should be inserted here ???? { display: none; } </style>") ...

Conceal the browser scrollbars

When I have two DIVs on my webpage that are larger than a browser window, it results in a horizontal scrollbar being displayed. How can I hide this browser scrollbar for the first DIV while still showing it for the second one? For example, if I have two ...

Positioning an item atop the curved exterior of a spinning Globe

I am new to posting here, so bear with me as I explain my issue. Whenever I place an object on a rotating sphere's surface, it becomes offset as the sphere continues to rotate. I have attempted to adjust the position back to the mouse, but unfortunat ...

What sets Express.js apart from koa2.js in handling asynchronous functions?

I've encountered a situation where I had to set up the router using Express, and it was functioning correctly with the following code: router.get('/',(req,res)=>{ queries.getAll().then(stickers=>{ res.json(stickers) }) ...

Create a CSS popup alert that appears when a button is clicked, rather than using

Is there a way to customize CSS so that the popup alert focuses on a button instead of just appearing like this? https://i.sstatic.net/r25fd.jpg I have implemented this type of validation for a text box: <div class="form-group"> <label class="co ...

Exploring the implementation of waterfall in a Node.js application

async.traverse(map, function(item, tnext){ async.waterfall([ function(wnext){ console.log("One"); //performing MongoDB queries db.collection.find().toArray(function(err){ if(err){ ...

What is the best way to horizontally align a floated image with its text positioned at the bottom?

I centered the images inside the "main-content" class, but I'm unsure if I did it correctly. Now, I also want to center the text, but using margin affects the images as well. Apologies for the messy code, I'm just a beginner. Below is the HTML5 ...

Is it accurate that JavascriptResult displays javascript on the page in a string format?

I am new to .NET MVC and have been experimenting with different return types in MVC. However, I am having trouble getting the JavaScriptResult to work. In my controller, I have the following code: public ActionResult DoSomething() { string s = ...

Using JS and d3.js to eliminate or combine duplicate connections in a d3.js node diagram

Hey there! Hello, I am new to working with js/d3.js and tackling a small project. Here are some of my previous inquiries: D3.js: Dynamically create source and target based on identical JSON values JS / d3.js: Steps for highlighting adjacent links My cu ...

Guide to passing parameters in the pop method of Ionic 2

When using the push method in Ionic2, I attempted to pass parameters like so: this.nav.push(SecondPage, { thing1: data1, thing2: data2 }); However, I'm curious if there is a way to pass parameters in the pop() method. ...

Querying for the presence of an ObjectId in an array in Mongoose

I'm developing a Node.js project that involves two models: User and Project. Below is the Schema for the Project model: const ProjectSchema = new mongoose.Schema({ name: { type: String, maxlength: 50, required: true, } ...

Completion status of circle loader: 100%

I am currently facing some challenges getting the circle loader to work correctly. Although I can handle basic animations, the code I found on CodePen is a bit more advanced than what I am used to. I am using it as a learning experience to understand how i ...

Having trouble retrieving the complete base64 encoded data through ajax

I am facing an issue with converting an audio blob to base64 and passing it through ajax to a php page for storage in an SQL server. However, the full base64 file is not being received in the MySQL database for some reason. Below is the code I am using to ...

Utilizing jQuery UI for Autocomplete Functionality with Objects

Currently, I am utilizing jQuery version 1.11.2 and attempting to implement the autocomplete widget to interpret a data array. The array consists of two individuals - Will Smith and Willem Dafoe. I anticipated that upon typing 'Wi' in the text fi ...

Trouble with NodeJS NPM

I'm encountering difficulty when trying to install npm packages. npm ERR! Windows_NT 6.3.9600 npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules&bso ...

Display the text field in Angular with the appearance of a password field, not an input field

I am currently working with Angular 8 for my Angular-Electron project. Within this application, I have a sensitive field labeled API-Key stored in tabular format that needs to be displayed on the user's account page. However, it must appear as a passw ...

Mongoose: Insert a new item into an array of objects within an object property

I need help adding an element to an existing array within an object field in my mongoose "Utilisateur" schema. This is what my schema looks like: https://i.sstatic.net/xv69M.png The goal is to insert a new element into the "lien_vers" array using the foll ...

Angular UI.Router's $state templates use $rootScope for ng-models

I'm encountering a strange issue where the ui-view template in my $state controller seems to be interacting with $rootScope instead of $scope. However, it does initialize $scope variables properly. For instance: if I have $scope.name = "test" and i ...