I'm trying to add a class to a parent <li>, this is what I have been trying with no result:
function calendaractive(){
$(this).parent('li').addClass("active");
}
HTML
<li>
<a href="javascript:void(0)" onclick="calendaractive();">2009</a>
</li>
Why does this not work?
Try.
Pass this at your function binding
<li>
<a href="javascript:void(0)" onclick="calendaractive(this);">2009</a>
</li>
change the JS accordingly
function calendaractive(anchorLink){
$(anchorLink).parent().addClass("active");
}
It's better to not mix your HTML and JavaScript. It would be better to check for the click within the JavaScript itself:-
$(document).ready(function(){
$('li > a').on('click', function(e) {
$(this).parent().addClass('active');
});
});
Keeping JavaScript separate from the HTML will make it easier to maintain (the same argument goes with CSS).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With