How to add a class to the parent element

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>

>Solution :

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();

Leave a Reply