If hasClass then addClass to parent
Asked Answered
S

6

6

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

Selfcentered answered 17/11, 2010 at 18:57 Comment(0)
O
30

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.

Ornis answered 17/11, 2010 at 18:58 Comment(0)
I
3

Alternatively you could use:

if ($('#navigation a').is(".active")) {
    $(this).parent().addClass("active");
}
Injurious answered 17/11, 2010 at 18:59 Comment(1)
$('#navigation a.active').parent().parent().addClass('active') would do the same thing. The conditional is something that can be handled with the selector.Leanto
P
0

You probably want to change the condition to if ($(this).hasClass('active'))

Also, hasClass and addClass take classnames, not selectors.
Therefore, you shouldn't include a ..

Podesta answered 17/11, 2010 at 18:58 Comment(0)
L
0

You can't use $(this) since jQuery doesn't know what it is there. You seem to be overcomplicating things. You can do $('#content h1.aktiv').hide(). There's no reason to test to see if the class exists.

Leanto answered 17/11, 2010 at 22:53 Comment(2)
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.Selfcentered
You can do $('#content h1.aktiv').parent().parent().addClass('aktiv') without conditionals.Leanto
I
0

The reason that does not work is because this has no specific meaning inside of an if statement, you will have to go back to a level of scope where this is defined (a function).

For example:

$('#element1').click(function() {
    console.log($(this).attr('id')); // logs "element1"

    if ($('#element2').hasClass('class')) {
        console.log($(this).attr('id')); // still logs "element1"
    }
});
Injurious answered 17/11, 2010 at 22:54 Comment(0)
S
0

If anyone is using WordPress, you can use something like:

if (jQuery('.dropdown-menu li').hasClass('active')) {
    jQuery('.current-menu-parent').addClass('current-menu-item');
}
Systematize answered 11/2, 2017 at 0:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.