zwitterion zwitterion - 7 months ago 28
Javascript Question

jQuery add and remove class in a multi level list

This is a list menu with 2 levels.

<ul id="mylist">
<li class="lv1"><a class="privateMenuLinkJS">el1.1</a></li>
<li class="lv1"><a>el1.2</a>
<ul>
<li class="lv2"><a class="privateMenuLinkJS">el1.2.1</a></li>
<li class="lv2"><a class="privateMenuLinkJS">el1.2.2</a></li>
<li class="lv2"><a class="privateMenuLinkJS">el1.2.3</a></li>
</ul>
</li>
<li class="lv1"><a class="privateMenuLinkJS">el1.3</a></li>
</ul>


Rules:


  1. Only elements "privateMenuLinkJS" can trigger the click event.

  2. Only elements level 1 (lv1) tagged must be tagged with "active".



If I click over el1.1 its parent "li" must be tagged with active and the others lv1 must have active class removed. Same for el1.2,el1.3

If I click over el1.2.1/1.2.2/1.2.3 its "lv1" grand parent "li" must be tagged with active and the others lv1 must have active class removed.

I have found this post jQuery: Same Level remove class but it not fit to my needs.

I've tried parents, http://api.jquery.com/parent/, I've tried each http://api.jquery.com/each/ but it seems that each do not loops trough the list element.

This is the code I have created so far http://jsfiddle.net/45xc2j1k/

I know the algorithm could be better.

Any idea how to perform that?

Answer

I think you have over-complicated it. On click you could just remove the active class from all lis and apply to the parent .lv1.

EG:

$(document).on("click", ".privateMenuLinkJS", function(e){
    e.preventDefault();
    //Remove ALL active class:
    $("#mylist .active").removeClass( "active" );
    //Add active class for is parent if it is level 1
    $( this ).parents(".lv1").addClass( "active" );    
});

http://jsfiddle.net/0bnk08nq/1/ (updated)

Comments