Home > database >  How to active a <li> in <ul> nested in jQuery?
How to active a <li> in <ul> nested in jQuery?

Time:06-04

I have a sidebar menu, some <li> have sub-options that you see in the code, my question is when I click on one of these <li> sub-options I want it to be activated, even after Page load is also enabled.How should I do this? This jQuery code I wrote only works for <li> without sub-options

<ul>
 <li>
 <a asp-page="/Index" ><i ></i><span> dashboard</span></a>
</li>
  <li >
   <a ><i ></i><span>  
    users</span><span ><i ></i></span></a>
    <ul >
     <li><a asp-page="/Account/Index"> user</a></li>
       <li><a asp-page="/AccountDelete/Index">  Delete
      </a></li>
     <li><a asp-page="/Accounts/Role/Index"> role </a></li>                                    
     </ul>
  </li> 
 </ul>

JQuery Code:

$("ul li a").each(function(){
 if ($(this).attr("href") == window.location.pathname){
   $(this).addClass("active");
 }
}); 

CodePudding user response:

Because of your selector, your loop doesn't check sub-options. Add a class like "menu-link" to 'a' tags and change your code like this.

$("a.menu-link").each(function(){
  if ($(this).attr("href") == 
    window.location.pathname){
    $(this).addClass("active");
  }
}); 

CodePudding user response:

You're looking for href attribute in your logic, and that seems to be what is causing the issue for you. Try looking for both href and asp-page attributes.

$("ul li a").each(function() {
  let $elm = $(this);
  if ($elm.attr("href") == window.location.pathname || $elm.attr("asp-page") == "/") {
    $(this).addClass("active");
  }
});
.active {
  font: 14px;
  font-weight:700;
  
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li>
    <a asp-page="/Index" ><i ></i>
    <span>Dashboard</span></a>
  </li>
  <li >
    <a >
      <i ></i>
      <span>Users</span>
      <span ><i ></i></span>
    </a>
    <ul >
      <li><a asp-page="/Account/Index">User</a></li>
      <li><a asp-page="/AccountDelete/Index">Delete</a></li>
      <li><a asp-page="/Accounts/Role/Index">Role</a></li>
      <li><a asp-page="/">Answer</a></li>     
    </ul>
  </li>
</ul>

  • Related