curly_brackets
curly_brackets

Reputation: 5598

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

Upvotes: 6

Views: 122078

Answers (6)

Edgar Quintero
Edgar Quintero

Reputation: 4441

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');
}

Upvotes: 0

Marcus Whybrow
Marcus Whybrow

Reputation: 19988

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"
    }
});

Upvotes: 0

Bill Criswell
Bill Criswell

Reputation: 32921

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.

Upvotes: 0

Marcus Whybrow
Marcus Whybrow

Reputation: 19988

Alternatively you could use:

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

Upvotes: 3

SLaks
SLaks

Reputation: 887275

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

Upvotes: 0

BoltClock
BoltClock

Reputation: 723448

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.

Upvotes: 30

Related Questions