If hasClass then addClass to parent

118,611

Solution 1

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.

Solution 2

Alternatively you could use:

if ($('#navigation a').is(".active")) {
    $(this).parent().addClass("active");
}
Share:
118,611
curly_brackets
Author by

curly_brackets

Updated on October 10, 2022

Comments

  • curly_brackets
    curly_brackets over 1 year

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

  • curly_brackets
    curly_brackets over 13 years
    I need a script, that finds out if there is an object with the class ".aktiv". If the class is found, the parents parents parent should be given the same class. The Edited part, with the if-sentence, is just something I stumpled upon - a bug, if you like, that I just wanted to hear you guys.
  • Bill Criswell
    Bill Criswell over 13 years
    You can do $('#content h1.aktiv').parent().parent().addClass('aktiv') without conditionals.
  • Bill Criswell
    Bill Criswell over 13 years
    $('#navigation a.active').parent().parent().addClass('active') would do the same thing. The conditional is something that can be handled with the selector.