skip to Main Content

I have li which contains a. When I click on a some action occurs and the active class is added.

I need that when clicking on a, the active class is added for li. Right now my code doesn’t work and doesn’t add any class. How can this be done?

$('a').click(function() {
  $('a').removeClass('active');
  $(this).addClass('active');
  $(this).parent().addClass('active');
});
li.active { border: 1px solid rebeccapurple }
a.active { color: red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li>
  <a>Link</a>
</li>

2

Answers


  1. It seems you code more or less works

    Perhaps this is what you want

    $('a').click(function() {
      $('a').removeClass('active');
      $('a').parent().removeClass('active');
      $(this).addClass('active');
      $(this).parent().addClass('active');
    });
    a.active {
      background-color: yellow
    }
    
    li.active {
      background-color: red
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <ul>
      <li>
        <a>Click</a>
      </li>
      <li>
        <a>Click</a>
      </li>
      <li>
        <a>Click</a>
      </li>
      <li>
        <a>Click</a>
      </li>
    </ul>

    NOTE that if the a navigates somewhere else that also has this navigation, it will not keep the class unless you use localStorage.

    If you want to stop it from navigating you can add

    $('a').click(function(e) {
      e.preventDefault();
    
    Login or Signup to reply.
  2. It looks like you have a working code, I did it and everything worked:

    $('a').click(function(e) {
      e.preventDefault();
      $('a').removeClass('active');
      $('li').removeClass('active');
      $(this).addClass('active');
      $(this).parent().addClass('active');
    });
    li.active {
      border: 1px solid rebeccapurple
    }
    
    a.active {
      color: red;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <ul>
      <li>
        <a class="active">Link</a>
      </li>
      <li>
        <a>Link</a>
      </li>
    </ul>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search