Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading