Radian Radian - 1 year ago 62
jQuery Question

Compare link href with address path for menu state

I'm working on right menu and i want to save that state with compare link

tag with address path location.

function setNavigation() {
var path = window.location.pathname;
path = path.replace(/\/$/, "");
path = decodeURIComponent(path);
$(".sidebar-menu li ul a").each(function () {
var href = $(this).attr('href');
if (path.substring(0, href.length) === href) {

The problem is that the code not recognize similar addresses in one

for example both of below item give


also here is my html

<li><a href="/Panel/Place" class="active-item"></a></li>
<li><a href="/Panel/Place/item" class="active-item"></a></li>
<li><a href="/Panel/Place/City"></a></li>
<li><a href="/Panel/Definitions/Attribute">/a></li>
<li><a href="/Panel/TouristDestination"></a></li>

Answer Source
  1. Correct : $(".sidebar-menu li ul a") to $(".sidebar-menu ul li a")

  2. I have changed the path matching method, check it out:

//sample path
var path = "www.xyz.com/Panel/Place";

function setNavigation() {
  path = path.substring(path.indexOf("/"), path.length);
  path = decodeURIComponent(path);
  $(".sidebar-menu ul li a[href='" + path + "']").addClass('active-item');

.active-item {
  color: red;
  background-color: #aaa;
li a {
  display: block;
  border: 1px solid #888;
  padding: 5px;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sidebar-menu">
    <li><a href="/Panel/Place">/Panel/Place</a></li>
    <li><a href="/Panel/Place/item">/Panel/Place/item</a></li>
    <li><a href="/Panel/Place/City">/Panel/Place/City</a></li>
    <li><a href="/Panel/Definitions/Attribute">/Panel/Definitions/Attribute</a></li>
    <li><a href="/Panel/TouristDestination">/Panel/TouristDestination</a></li>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download