Search code examples
jqueryparent

What's wrong with my jQuery code finding the first parent?


I'm developing a small app which haves a tree view menu, so this is the html:

<ul class="sidebar-menu">
    <li class="active"><a href="javascript:;"> ELEMENT 1 </a></li>
    <li class="treeview">
        <a href="javascript:;"> ELEMENT 2 <span class="pull-right-container"><i class="fa fa-angle-left pull-right"></i></span></a>
        <ul class="treeview-menu">
            <li><a href="javascript:;"> ELEMENT 2.1 </a></li>
            <li><a href="javascript:;"> ELEMENT 2.2 </a></li>
        </ul>
    </li>
    <li><a href="javascript:;"> ELEMENT 3 </a></li>
</ul>

I'm trying to highlight the clicked li element adding the .active class to it. But, when you click on a subelement, I want to highlight also the parent. For example, if you click the ELEMENT 2.1 I want to highlight also the ELEMENT 2.

This is my jQuery code to get, first the clicked element, and then it's li parent (I can't do ir without the :not selector for other reasons:

$(".sidebar-menu").on("click", "li:not(.treeview)", function(e){
    $(e.delegateTarget).parents("li").first();
}

The if statement works as expected, but the second line always give me a undefined error in the console.


Solution

  • Working Fiddle.

    You could use the jQuery object $(this) that refer to the current clicked element then addClss() to add class active class :

    $(this).parents('li').addClass('active');
    

    NOTE : you have to use $('li').removeClass('active'); to remove active class from all the other li's`.

    Hope this helps.

    $(".sidebar-menu").on("click", "li:not(.treeview)", function(e){
      //remove active class from all the other li's
      $('li').removeClass('active');
     
      $(this).addClass('active'); //add active class to the clicked li
    
      //Add active class to the parent if exist
      if( $(this).parents('li').length > 0)
          $(this).parents('li').addClass('active');
    })
    .active{
      background-color: yellow;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <ul class="sidebar-menu">
      <li class="active"><a href="javascript:;"> ELEMENT 1 </a></li>
      <li class="treeview">
        <a href="javascript:;"> ELEMENT 2 <span class="pull-right-container"><i class="fa fa-angle-left pull-right"></i></span></a>
        <ul class="treeview-menu">
          <li><a href="javascript:;"> ELEMENT 2.1 </a></li>
          <li><a href="javascript:;"> ELEMENT 2.2 </a></li>
        </ul>
      </li>
      <li><a href="javascript:;"> ELEMENT 3 </a></li>
    </ul>