0

I want prevent default and add an active class to the parent links of a list in a dropdown menu. The code i have is this:

Markup:

<ul class="subNavMobile">
    <li>
        <a href="#">link parent</a>
        <ul>
            <li><a href="anurl.html">child link</a></li>
        </ul>
    </li>
    <li><a href="#">link parent2</a></li>
    <li><a href="#">link parent3</a></li>
</ul>

jQuery:

$('.subNavMobile > li a').on('click', function (e) {
    var parent = $(this).parent();
    if (!parent.hasClass('active')) {
        parent.parent().find('li.active').removeClass('active');
        parent.addClass('active');
    } else {
        parent.removeClass('active');
    }
});

But this is also affectiong to the child list and this is not desired. How do I only add the class and prevent default in just the parents and not in the child? Thank you.

4
  • exactly that DavidThomas. Sorry ^^' Commented Jul 5, 2014 at 18:16
  • No problem; that was my first thought but it was one of those errors that could either be a typo (as it was) or part of the problem itself... Commented Jul 5, 2014 at 18:17
  • Should clicking the child activate the topmost parent? Commented Jul 5, 2014 at 18:25
  • No, when clicking a list item in subNavMobile an active class should be added to that list item and be removed in its siblings. The children list items of that list items(parent) shouldn't have this behavior Commented Jul 5, 2014 at 18:30

1 Answer 1

1

Change your selector to:

$('.subNavMobile > li > a')

Your selector matches a that is anywhere inside .subNavMobile > li, but you only want the a that is a direct child of it.

And to prevent the default, put

e.preventDefault();

in the function.

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

Comments

Your Answer

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