-2

HTML:

<ul class="navbar-nav">
    <li class="nav-item active">
        <a class="nav-link" href="/Home/ProductAndServices">
        ProductAndServices
        </a>
    </li>
    <li class="nav-item">
        <a class="nav-link" href="/Home/EligibilityCriteria">
        EligibilityCriteria
        </a>
    </li>                            
</ul>

Changing <li> element's class to 'active' by following code:

$('.navbar-nav li a').on('click', function () {
    $('.navbar-nav li.active').removeClass('active');
    $(this).parent().addClass('active');
});

is giving no error inside console, but not giving desired output.

Someone please help. Thanks in advance.

13
  • Please add your HTML preferably as a minimal reproducible example Commented May 23, 2022 at 5:12
  • What do you get when you console log $(this)? Commented May 23, 2022 at 5:22
  • cannot reproduce it. Please provide the code that reproduces the issue. Commented May 23, 2022 at 5:25
  • 1
    If you are navigating via href how would your on click work? It navigates or reloads Commented May 23, 2022 at 5:31
  • 1
    It makes no difference, when a new page is loaded in the browser, it is a brand new page, regardless of shared layout. New URL , new page. Commented May 23, 2022 at 6:41

1 Answer 1

0

This might work:

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

I believe you're trying to refer to the parent element which is not a function. Maybe that's why the code doesn't work!

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

3 Comments

jQuery does support .parent(). At least I used to remember that, it's been so long now since I last used it
It still exists .parent()
this is not working

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.