First of all lets consider what HTML we will be working with. A Html.ActionLink
will convert into an a
tag, so your HTML will look something like this:
<li class="navItem"><a href="/Home/Index">Home</a></li>
With that in mind we can iterate the li
elements, check their inner a
element and match on the href
attribute.
So something like this should work:
function currentItem() {
var actionName = '@ViewContext.RouteData.Values["Action"].ToString()';
var controllerName = '@ViewContext.RouteData.Values["Controller"].ToString()';
var listItems = $('.navItem');
for(var i = 0; i < listItems.length; i++){
var item = $(listItems[i]);
var a = item.find("a");
if(a.attr["href"].indexOf(controllerName + "/" + actionName) != -1){
return item;
}
}
}
Note that this will return the matching li
element. If you want the matching a
element then use return a;
instead.