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
It seems you code more or less works
Perhaps this is what you want
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
It looks like you have a working code, I did it and everything worked: