0

I have an angular directive that displays a treeview. When you click on the li icons it is supposed to hide the nested ULs.

Here's the code that matters: (this is in a click function where e is the click event)

$toggler=$(e.target).closest('li');
if($toggler.hasClass("collapsed")){
 $toggler.removeClass("collapsed").addClass("expanded");
} else {
  $toggler.removeClass("expanded").addClass("collapsed");
}
$(".collapsed").find("ul").hide();
$(".expanded").find("ul").show();

I can see in the debugger that the class is being assigned and removed properly. However, it only works for the first set of LIs where I initially set the class as collapsed. The deeper levels of the tree are showing the class changes but the selector doesn't work with them. Interestingly, when you click on a deeper row it acts like you're clicking the root row the first time. after that it does nothing.

The question: Why isn't my selector working?

here's my plunkr: http://plnkr.co/edit/GZ5MZjkir4AaNQmHIxFP?p=preview

1 Answer 1

1

The problem is that you first apply .collapsed and then .expanded. So your children are always expanded if the root is expanded. If you swap them, it works like intended:

$(".expanded").find("ul").show();
$(".collapsed").find("ul").hide();

So it first expands all the children. Then it reaches the first .collapsed child, collapses it. After this continues collapsing .collapsed children bringing no visual difference.

Sign up to request clarification or add additional context in comments.

1 Comment

ah I see, find returns any child, grand child etc. down the chain, not just the direct descendents. that works!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.