0

This is what's happening in my boostrap menu. When I click any item in the dropdown the child is selected (class="active") but the parent is not. So, if the dropdown is closed you can't see in the menu the selected page.

<ul class="nav navbar-nav navbar-right">
  <li class="my-class"><a href="#">Home</a></li>
     <ul role="menu" class=" dropdown-menu">
      <li class="active"><a href="#">Brokerage</a></li>
      <li class="my-other-class"><a href="#">Consulting</a></li>
    </ul>
  </li>
  <li class="my-class"><a href="#">Contact Us</a></li>
</ul>

I'm trying to do it with this but it's not working:

$('li').click(function() {
 $(this).parents().addClass('.active');  
});

Any help? Thanks.

1
  • 1
    It's not clear what you are asking.It's worth pointing out the the parent of the li is the ul...not the li holding the dropdown.
    – Paulie_D
    Mar 8, 2014 at 19:53

2 Answers 2

1

You shouldn't put the . in the class name you pass to addClass. Also, parents() selects all its ancestors. If you just want the direct parent, use parent() (without 's').

 $(this).parent().addClass('active'); 
1

You have some mistakes in your jQuery:

$('li').click(function() {
   $(this).parent().addClass('active');  
});

1.) It is parent() in your case, not parents().

2.) addClass('active')is correct, not addClass('.active').

Bootply Example

4
  • +1 for being 15 seconds faster than me. ;) But you still got the 'period' bug in you Bootply Example.
    – GolezTrol
    Mar 8, 2014 at 19:57
  • ha, you are correct! Somehow my fork didn't apply the change. Thanks for pointing it out, I corrected it and thanks for the +1 :) Mar 8, 2014 at 20:01
  • @Sebsemillia In your Bootply 'Brokerage' (under Services) is highlighted but 'Services' is not and that is what I'm trying to do. Thanks.
    – Labanino
    Mar 8, 2014 at 20:22
  • Try this: bootply.com/120146. I changed your jQuery and added the nav element in your HTML, which Bootstrap needs. Mar 8, 2014 at 20:44

Not the answer you're looking for? Browse other questions tagged or ask your own question.