curly_brackets
curly_brackets

Reputation: 5598

If statement fails with $(this), but works with absolute

I ran into this very odd scenario. This won't hide the H1:

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

Only this will:

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

Why can't I use the (this)? Is something wrong with the script?

Upvotes: 0

Views: 80

Answers (4)

Timothy S. Van Haren
Timothy S. Van Haren

Reputation: 8966

The statement $('#content h1').hasClass('active') returns a Boolean value (true or false), as opposed to a jQuery object, which is what you're trying to use $(this) for. See the usage of hasClass here.

If you're trying to perform an action on all elements that match a certain selector, give this selector a try instead:

$("#content h1.active").hide();

This finds all elements with an id attribute of "content" that contain an h1 element with a class attribute of "active," and hides them all.

Upvotes: 0

Sam
Sam

Reputation: 615

What you want is probably

var h1 = $('#content h1')
if (h1).hasClass('active')) {
    h1.hide();
}

your "this" will, as stated above, not reference your object.

Upvotes: 0

Vincent Mimoun-Prat
Vincent Mimoun-Prat

Reputation: 28541

You could do:

$('#content h1').foreach(function() {
    if (!$(this).hasClass('active')) {
        $(this).hide();
    }
});

In this case, as Jan explained, this will be in the context you expect it to be (the heading element).

Upvotes: 0

Jan Hančič
Jan Hančič

Reputation: 53931

That is the correct behaviour. In the context of your if statement this does not hold a reference to your h1 element but to the document element (or function if you are inside of a function).

Upvotes: 3

Related Questions