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?