Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AddClass to parent <li> on function

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?


2 Answers

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");
}
like image 101
asifsid88 Avatar answered Dec 08 '25 07:12

asifsid88


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).

like image 40
drmonkeyninja Avatar answered Dec 08 '25 07:12

drmonkeyninja



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!