Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If hasClass then addClass to parent

Original post: Why doesn't this simple script work?

if ($('#navigation > ul > li > ul > li > a').hasClass('.active')) {
    $(this).parent().parent().parent().addClass(".active");
}

EDIT:

This won't hide the H1:

if ($('#content h1').hasClass('aktiv')) {
    $(this).hide();
}

Only this will:

if ($('#content h1').hasClass('aktiv')) {
    $('#content h1').hide();
}

Why can't I use the (this)?

like image 225
curly_brackets Avatar asked Nov 17 '10 18:11

curly_brackets


2 Answers

The dot is not part of the class name. It's only used in CSS/jQuery selector notation. Try this instead:

if ($('#navigation a').hasClass('active')) {
    $(this).parent().addClass('active');
}

If $(this) refers to that anchor, you have to change it to $('#navigation a') as well because the if condition does not have jQuery callback scope.

like image 102
BoltClock Avatar answered Oct 20 '22 20:10

BoltClock


Alternatively you could use:

if ($('#navigation a').is(".active")) {
    $(this).parent().addClass("active");
}
like image 40
Marcus Whybrow Avatar answered Oct 20 '22 21:10

Marcus Whybrow